我正在尝试对数据帧中的变量进行变异,该数据帧中有我正在使用的数据集中55个变量中的10个。这10个变量中有5个是分类的,因此,我试图将它们转换为因子(作为字符(。然而,每次R进行突变时,它都会将突变应用于这5个因素,就好像我从未将它们放入单独的数据框架中一样。R将仅在整个55个变量组中对它们应用突变。我已经多次突出显示并重新运行代码作为一个整体,并为每个变量单独运行,但它仍然不起作用。当我对我想要的十个变量使用(view(函数,并将每个变量名悬停在显示的表中时,由于某种原因,突变会消失,就好像我没有这样做一样。当我在整个数据集上使用(视图(并进行同样的操作时,突变就在那里。我创建了多个数据帧,只是为了让它发挥作用。我想也许我必须再次移动变量,然后突变就会出现,但事实并非如此。
现在我也遇到了R只应用一个突变的问题。如果我试图使变量";qualslp";从数字到字符,然后对变量";性;r去除了"r"上的突变;qualslp";并且它返回到数字;性;成为字符矢量。
下面提供了代码和屏幕截图。
带有一个突变的55个变量的屏幕截图(黄色下划线(
包含我想在上使用突变函数的10个变量的数据框的屏幕截图(黄色下划线(
sleepdata_nvars <-select(sleepdata,
age, sex, alchohol, smokenum, liteslp, wakenite, medhelp, qualslp, depress, ess)
sleepdata_nvars <- mutate(sleepdata,
sex = as.character(sex),
sex = fct_recode(sex,
"female" = "0",
"male" = "1"))
sleepdata_nvars <- mutate(sleepdata,
liteslp = as.character(liteslp),
liteslp = fct_recode(liteslp,
"yes" = "1",
"no" = "2"))
sleepdata_nvars <- mutate(sleepdata,
wakenite = as.character(wakenite),
wakenite = fct_recode(wakenite,
"yes" = "1",
"no" = "2"))
sleepdata_nvars <- mutate(sleepdata,
medhelp = as.character(medhelp),
medhelp = fct_recode(medhelp,
"yes" = "1",
"no" = "2"))
sleepdata_nvars <- mutate(sleepdata,
qualslp = as.character(qualslp),
qualslp = fct_recode(qualslp,
"very poor" = "1",
"poor" = "2",
"fair"= "3",
"good" = "4",
"very good" = "5",
"excellent" = "6"))
根据@MichaelDewar的评论,我认为问题是您应该只使用一个mutate
语句,并将其链接到原始的select
。
sleepdata_nvars <- sleepdata %>%
select(age, sex, alchohol, smokenum, liteslp,
wakenite, medhelp, qualslp, depress, ess) %>%
mutate(sex = as.character(sex),
sex = fct_recode(sex,
"female" = "0",
"male" = "1"),
liteslp = as.character(liteslp),
liteslp = fct_recode(liteslp,
"yes" = "1",
"no" = "2"),
wakenite = as.character(wakenite),
wakenite = fct_recode(wakenite,
"yes" = "1",
"no" = "2"),
medhelp = as.character(medhelp),
medhelp = fct_recode(medhelp,
"yes" = "1",
"no" = "2"),
qualslp = as.character(qualslp),
qualslp = fct_recode(qualslp,
"very poor" = "1",
"poor" = "2",
"fair"= "3",
"good" = "4",
"very good" = "5",
"excellent" = "6")
)