根据r中多个列中的值创建组

  • 本文关键字:创建组 根据 r dplyr mutate
  • 更新时间 :
  • 英文 :


我有一个这样的数据帧:

ID <- c("A", "B", "C", "D", "E", "F")
Score1 <- c("(25-30)", "(31-40)", "(41-60)", "(25-30)","(25-30)","(25-30)")#(25-30) low problems cut-off
Score2 <- c("(0-5)", "(6-11)", "(25-30)", "(6-11)", "(0-5)", "(0-5)") #"(0-5)" low problems cut-off
Score3 <- c("(12-20)", "(21-42)", "(43-55)", "(12-20)", "(21-42)","(12-20)")#"(12-20)" low problems cut-off
Score4 <- c("(1-20)", "(21-60)", "(61-80)", "(1-20)", "(1-20)", "(1-20)")#"(1-20)" low problems cut-off
df <- data.frame(ID, Score1, Score2, Score3, Score4)

我想根据得分1到4的类别创建分组。

这些评分类别是我的临界值,分为低问题、中等问题和高问题。

这个想法是,只要参与者属于中等或高问题类别之一,他们就会进入实验组,而那些属于所有得分低问题类别的人将进入对照组。

这就是为什么,我尝试了下面一个朋友建议的东西,但我的问题有点不同,我想这就是为什么它在不同的逻辑上工作。

下面我想告诉R把所有分数中属于第一个得分类别的人归为对照组,而其他人归为实验组。

df <- df %>%
mutate(Group = case_when(
Score1 == "(25-30)" | Score2 == "(0-5)" | Score3 == "(12-20)" | Score4 == "(1-20)"
~ "Control", 
TRUE ~ "Experimental" ))

但这是你最后得到的:

ID  Score1  Score2  Score3  Score4        Group
1  A (25-30)   (0-5) (12-20)  (1-20)      Control
2  B (31-40)  (6-11) (21-42) (21-60) Experimental
3  C (41-60) (25-30) (43-55) (61-80) Experimental
4  D (25-30)  (6-11) (12-20)  (1-20)      Control
5  E (25-30)   (0-5) (21-42)  (1-20)      Control
6  F (25-30)   (0-5) (12-20)  (1-20)      Control

如你所见,参与者D和E在对照组中,尽管参与者D的Score2和参与者E的Score3在中等临界值中,换句话说,我没有在代码中指定得分组。

只有当参与者不在所有分数的低问题分界点时,它才会将他们带到实验组。我应该如何修改我的代码?

很抱歉我的问题很长。非常感谢!

恕我直言,检查所有分数是否都在较低组更容易,即使用&if_else,您可以这样做:

library(dplyr, warn = FALSE)
df |> 
mutate(Group = if_else(Score1 == "(25-30)" & Score2 == "(0-5)" & Score3 == "(12-20)" & Score4 == "(1-20)", "Control", "Experimental"))
#>   ID  Score1  Score2  Score3  Score4        Group
#> 1  A (25-30)   (0-5) (12-20)  (1-20)      Control
#> 2  B (31-40)  (6-11) (21-42) (21-60) Experimental
#> 3  C (41-60) (25-30) (43-55) (61-80) Experimental
#> 4  D (25-30)  (6-11) (12-20)  (1-20) Experimental
#> 5  E (25-30)   (0-5) (21-42)  (1-20) Experimental
#> 6  F (25-30)   (0-5) (12-20)  (1-20)      Control

最新更新