简体   繁体   中英

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. I received information about which IDs in my analysis had the diagnosis and I want to create a column indicating that.

My data frame looks like this(normally Ids are longer and a random mixture of numbers and letters:

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. 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.

Thanks in advance!

Not sure what you tried exactly then..This works?

df %>%
  mutate(Diagnosis = if_else(ID %in% c("a2", "d4"), 1, 2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM