0

我正在尝试折叠因子水平,最初,count(a7_edu2)输出显示折叠已经起作用,但是当我检查结构并查看 RStudio 视图时,更改不会影响实际变量。

关于保存为新变量或覆盖旧变量的任何建议?谢谢!

我曾经fct_collapse折叠成三个类别并尝试mutate()使用新级别创建一个新变量。我已经尝试保存到一个新变量中,并且还保存了 transmute() 而不是 mutate()。我会对新变量或替换旧变量感到满意。

  mutate(a7_edu2 = fct_collapse(a7_edu2,
    Highschool = c("Elm School", "Grade 7 or 8", "Grade 9 to 11", "High School Diploma", "G.E.D"),
    Diploma = c("Diploma or Certificate from trade tech school" , "Diploma or Certificate from community college or CEGEP"),
    Bachelors = c("Bachelor degree", "Degree (Medicine, Dentistry etc)", "Masters degree", "Doctorate")
  )) %>%
  count(a7_edu2) # this is the result I want but when i check the structure, it doesn't save!


str(SCI_dem$a7_edu2)

我预计输出是“具有 4 个级别“高中”、“文凭”、“学士”、“其他”的因子,但它给出了原始的“具有 13 个级别“榆树学校”、“7 级或 8 级”的因子,..: 8 7 6 10 7 7 8 3 7 10 ..."


更新的问题:它可以将一个变量保存到新的 df ( SCI_collpase) 中。但是,当我尝试将其他新的折叠变量保存到同一个数据框时,它会覆盖以前的折叠...我尝试指定新列SCI_collapse$edu,但随后它重命名了 df 中的现有变量...如何折叠多个变量并添加它们每个到一个新的df? 保存或编写管道的建议?

SCI_collapse <- SCI_dem %>% 
  mutate(a7_edu2 = fct_collapse(a7_edu2, 
                                Highschool = c("Elm School", 
                                                        "Grade 7 or 8", 
                                                        "Grade 9 to 11", 
                                                        "High School Diploma", 
                                                        "G.E.D"), 
                                Diploma = c("Diploma or Certificate from trade tech school" , 
                                            "Diploma or Certificate from community college or CEGEP"), 
                                Bachelors = c("Bachelor degree", 
                                              "Degree (Medicine, Dentistry etc)", 
                                              "Masters degree", "Doctorate")))
4

1 回答 1

0

这就是我最终做的事情:

# Collapse levels (education) SCI_dem <- SCI_dem %>% mutate(a7_edu2_col = fct_collapse(a7_edu2, # Save as new variable ending in _col Highschool= c("Elm School", "Grade 7 or 8", "Grade 9 to 11", "High School Diploma", "G.E.D"), Diploma = c("Diploma or Certificate from trade tech school" , "Diploma or Certificate from community college or CEGEP"), Bachelors= c("Bachelor degree", "Degree (Medicine, Dentistry etc)", "Masters degree", "Doctorate"), Other = c("Other", "Prefer not to answer") ), a7_edu2_col = droplevels(a7_edu2_col)) %>% # drop empty levels of _col rename(a7_edu2_unc = a7_edu2)

我现在有以结尾的变量_col并将变量重命名为以结尾_unc(未折叠)。然后我通过删除以_unc.

SCI_dem <- select(SCI_dem, -ends_with("_unc"))

这给我留下了整洁、折叠的数据框:)

于 2019-06-12T00:51:17.833 回答