我有一个大型数据集(名为'cud1'),我想在其中添加一个新列,将多个主要健康投诉分类为更简单的健康类别('q2.2_healthCat')。也就是说,初级健康投诉1、2、4或6将被归类为“精神健康”(第1类),答复3、5、7或8=疼痛(第2类),所有其他答复(9、10、11、12)将被归类为其他(第3类)。这是一个基本的数据框架,让你有一个概念:
Participant_ID <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Primary_health_complaint <- c(3, 7, 12, 11, 3, 1, 9, 4, 6, 2)
cud1 <- data.frame(Participant_ID, Primary_health_complaint)然后我想要一个新的专栏写道:
q2.2_healthCat <- c(2, 2, 3, 3, 2, 1, 3, 1, 1, 1)下面是我的尝试(这次使用case_when ):
cud1 <- cud1 %>% mutate(q2.2_healthCat = case_when(
primary_health_complaint = c(1,2,4,6), '1',
primary_health_complaint = c(3,5,7,8), '2',
primary_health_complaint = c(9,10,11,12), '3')) 希望有人能帮忙!请善待我,因为我是R的新手。我已经看了很多其他的帖子,但我不知道我做错了什么。
编辑:在这里case_when in mutate pipe找到了解决方案,使用了以下内容:
require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]发布于 2020-12-04 09:44:31
也许您可以尝试使用下面的嵌套ifelse
within(cud, q2.2_healthCat <- ifelse(Primary_health_complaint %in% c(1, 2, 4, 6), 1, ifelse(Primary_health_complaint %in% c(3, 5, 7, 8), 2, 3)))这给了我们
Participant_ID Primary_health_complaint q2.2_healthCat
1 1 3 2
2 2 7 2
3 3 12 3
4 4 11 3
5 5 3 2
6 6 1 1
7 7 9 3
8 8 4 1
9 9 6 1
10 10 2 1https://stackoverflow.com/questions/65136724
复制相似问题