0
votes

Don't see another question like this one. I've used mutate to create new variables, but can't find a tutorial that shows how to do this: I'm trying to add +2 to the hsi value if the con value is NALFD

con <- c('NALFD', 'NALFD', 'NALFD', 'NASH', 'NASHCC')
hsi <- c(45.71571, 37.09238, 48.89828, 46.37123, 39.8328)
df <- data.frame(con, hsi)

So hsi should be: 47.71571, 39.09238, 50.89828, 46.37123, 39.8328

Thanks.

1

1 Answers

0
votes

You can use if_else -

library(dplyr)

df <- df %>% mutate(hsi = if_else(con == 'NALFD', hsi + 2, hsi))
df
#     con      hsi
#1  NALFD 47.71571
#2  NALFD 39.09238
#3  NALFD 50.89828
#4   NASH 46.37123
#5 NASHCC 39.83280

Also in base R -

df <- transform(df, hsi = ifelse(con == 'NALFD', hsi + 2, hsi))