这可能是基本的。考虑一个数据框:
df<-data.frame(year=c(2006:2015),
one=rep(2010,10),
two=rep(2011,10),
three=rep(2012,10))
Run Code Online (Sandbox Code Playgroud)
其中one是事件一发生的年份,two是事件二发生的年份,three是事件三发生的年份。我想构造一个变量ha,如果这些事件发生最多 2 年,则该变量取值 1,否则取值 0。
例如,在 2009 年,这些事件都没有发生,因此ha2009 年应该为 0。在 2015 年,距离事件三发生已有 3 年,距离事件一发生已有 5 年,因此ha应该为 0。但在 2011 年,事件一发生了去年发生,事件二刚刚发生,所以ha2011 年应该是 1。
最终结果应如下所示ha:
0 0 0 0 1 1 1 1 1 0
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用if_elsedplyr 来评估多个“或”条件时,我未能获得所需的结果。这是我的代码:
df<-df%>%
mutate(
ha=if_else(year-one%in%c(0,1,2)|year-two%in%c(0,1,2)|year-three%in%c(0,1,2),1,0)
)
Run Code Online (Sandbox Code Playgroud)
我想知道我的错误在哪里。
小智 7
你的问题是优先级。%in%首先评估 ,因此它计算而one%in%c(0,1,2)不是year-one%in%c(0,1,2)。解决方案是将括号括起来year - one:
df%>%
mutate(
ha=if_else((year-one)%in%c(0,1,2)|(year-two)%in%c(0,1,2)|(year-three)%in%c(0,1,2),1,0)
)
Run Code Online (Sandbox Code Playgroud)