r - 如何将折叠的因子水平(用于多个变量)保存到新的数据框中?
问题描述
我正在尝试折叠因子水平,最初,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")))
解决方案
这就是我最终做的事情:
# 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"))
这给我留下了整洁、折叠的数据框:)
推荐阅读
- python - “cv2.FlannBasedMatcher”对象没有属性“knnMatches”
- node.js - 切换到 API v2 时的 Dialogflow 编码问题
- angular - html中的Angular 4/5图像路径
- javascript - 如何在angularJS中使用URL下载PDF文件
- linux - postgres:无效参数:“psql”
- javascript - 在 JS 中将 12h 格式转换为 24h 格式
- javascript - 结帐opencart上的必填复选框
- r - 根据R中另一列中的值替换一列中第二次出现的字符串
- python - django-login-required-middleware WSGI 错误
- c# - 数字对象之间的 C# 加法