[英]adding a new column based on character values of another column in R
I want to add a new column to my dataset based on IDs.我想根据 ID 向我的数据集添加一个新列。 I received information about which IDs in my analysis had the diagnosis and I want to create a column indicating that.
我收到了关于我的分析中哪些 ID 进行了诊断的信息,我想创建一个列来表明这一点。
My data frame looks like this(normally Ids are longer and a random mixture of numbers and letters:我的数据框看起来像这样(通常 ID 更长,并且是数字和字母的随机混合:
ID <- c("a1", "a2", "a3", "b2", "b3", "d4")
score <- c(23,35,45,57,83,90)
df <- data.frame(ID, score)
df
ID score
a1 23
a2 35
a3 45
b2 57
b3 83
d4 90
And let's say I know that a2 and d4 have the diagnosis and want to assign them "1" in the new "diagnosis" column and "2" to the rest.假设我知道 a2 和 d4 有诊断,并希望在新的“诊断”列中将它们分配为“1”,将“2”分配给 rest。 So, I want to have something like this:
所以,我想要这样的东西:
ID score Diagnosis
a1 23 2
a2 35 1
a3 45 2
b2 57 2
b3 83 2
d4 90 1
I tried with dplyr, mutate and if else but couldn't achieve.我尝试使用 dplyr,变异,如果其他但无法实现。
Thanks in advance!提前致谢!
Not sure what you tried exactly then..This works?不确定你当时到底尝试了什么..这行得通吗?
df %>%
mutate(Diagnosis = if_else(ID %in% c("a2", "d4"), 1, 2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.