Title: increase numeric value of variable based on level of categorical variable
Tags: r;variables;dplyr
Question: 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.

Here is the accepted answer: You can use if_else -
library(dplyr)
df <- df %&gt;% mutate(hsi = if_else(con == 'NALFD', hsi + 2, hsi))
#     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))
Comment for this answer: Not working with my full dataset with 158 rows m % dplyr75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0mutate(HSI = if_else(Indication == 'NALFD', HSI+ 2, HSI))
glimpse(m), 45.71571, 37.09238 - 37 should be 39, the first one is not NALFD
Comment for this answer: Seems using "" instead of '' around NAFLD did the trick. Does that make sense?
Comment for this answer: Ronak - you removed your comment. I wanted to respond. WHat was it again?
Comment for this answer: works, must have been a typo but here is a subset -- sub <-
structure(list(Indication = c("NASH", "NAFLD", "NAFLD", "NAFLD",
"NAFLD"), HSI = c(45.7157137377985, 39.0923846783179, 50.8982846959234,
48.3712321740023, 41.8328741965106)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:07/12/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<r><variables><dplyr>', 'Title': 'increase numeric value of variable based on level of categorical variable', 'ViewCount': 33, 'id': 68342318, 'user_AboutMe': None, 'user_AccountId': 5571245.0, 'user_DisplayName': 'JuanTamad', 'user_Reputation': 65.0, 'user_Views': 25.0, 'user_id': 5242442.0}}