R Wd
R Wd

Reputation: 59

How can I combine mutate and an IF statement together?

I've written the following code:

df <- df %>% 
  mutate(relyear = (dealyear-firsttreat))

It works well, however in some cases the companies I'm examining do not have a year value in 'firsttreat' they just have a 0. This means the new 'relyear' variable is computed using 'dealyear' - 0.

How can I incorporate an IF statement, or adjust the code to say > if "firsttreat" = 0, then use 0 in the 'relyear' variable?

Thanks!

Upvotes: 0

Views: 80

Answers (1)

MonJeanJean
MonJeanJean

Reputation: 2906

This should do the trick:

df <- df %>% 
  mutate(relyear = ifelse(firsttreat == 0,0,dealyear-firsttreat))

Upvotes: 2

Related Questions