[英]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.它运行良好,但是在某些情况下,我正在检查的公司在“firsttreat”中没有年份值,它们只有 0。这意味着新的“relyear”变量是使用“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?如何合并 IF 语句,或调整代码以说 > 如果“firsttreat” = 0,然后在 'relyear' 变量中使用 0?
Thanks!谢谢!
This should do the trick:这应该可以解决问题:
df <- df %>%
mutate(relyear = ifelse(firsttreat == 0,0,dealyear-firsttreat))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.