我正在练习一个数据集,其中我有一个变量S6。它包含6个级别/因素。该变量table如下所示:
bachelor values
BBA 291
CSE 10
Math 1
Economics 33
Botany 498
Pharmacy 333我想重新对这个变量进行分类。如下所示:
Pharmacy, Botany = Life Science
BBA, CSE, Math, Economics = Others或,
Pharmacy, Botany = 1
BBA, CSE, Math, Economics = 2我尝试了这种技术来对这个变量进行重新分类:
bachelor[S6 %in% c("Pharmacy")] <- "Life Science"
bachelor[S6 %in% c("Botany")] <- "Life Science"
bachelor[S6 %in% c("BBA")] <- "Other"
bachelor[S6 %in% c("CSE")] <- "Other"
bachelor[S6 %in% c("Economics")] <- "Other"
bachelor[S6 %in% c("Math")] <- "Other"这项技术实际上对我很有效。但是,对于一个有超过10个因子或水平的变量来说,这是不现实的。
请建议我一些更有效的方法来重新分类变量。
发布于 2020-03-30 22:22:22
%in%函数可以在右侧接受多个变量名。所以你可以这样做:
bachelor[S6 %in% c("Pharmacy", "Botany")] <- "Life Science"
bachelor[S6 %in% c("BBA", "CSE", "Economics", "Math")] <- "Other"或者,您可以创建一种用于翻译的字典,并使用match
dict <- c(Pharmacy="Life Science",
Botany="Life Science",
BBA="Other",
CSE="Other",
Economics="Other",
Math="Other")
bachelor <- dict[match(S6, names(dict))]或者,使用外部包:
library(lest)
bachelor <- case_when(S6 %in% c("Pharmacy", "Botany")] ~ "Life Science",
S6 %in% c("BBA", "CSE", "Economics", "Math") ~ "Other",
TRUE ~ "Rest"
)https://stackoverflow.com/questions/60932535
复制相似问题