基于R中其他列的任何滞后值突变列



我对本应是一项非常简单的数据转换任务有一些问题。我有一个看起来像这样的数据帧:

df
council_name year treat
1    Southwark 2008     1
2    Southwark 2009     0
3    Southwark 2010     1
4      Lambeth 2006     0
5      Lambeth 2007     1
6      Lambeth 2008     0
7    Yorkshire 2006     0
8    Yorkshire 2007     0
9    Yorkshire 2008     0

我正在尝试获得一个新的变量,比如pre.post,如果一个委员会在year的任何较低值下,treat具有1的值。基本上,如果council在任何先前的yeartreat == 1具有pre.post == 1,则我想要CCD_6。

这就是我要找的:

df.desired
council_name year treat pre.post
1    Southwark 2008     1        1
2    Southwark 2009     0        1
3    Southwark 2010     1        1
4      Lambeth 2006     0        0
5      Lambeth 2007     1        1
6      Lambeth 2008     0        1
7    Yorkshire 2006     0        0
8    Yorkshire 2007     0        0
9    Yorkshire 2008     0        0

基本上,所有在任何之前时间处理==1的委员会都会获得pre.post==1。我尝试了不同的东西,比如:

library(dplyr)
df%>%
group_by(council_name)%>%
arrange(year)%>%
mutate(pre.post = ifelse(any(lag(year) = 1), 1, 0))

但似乎没有什么能得到我想要的。谢谢

等价地,找到第一个治疗年份,并将1分配给之后的每一年。

df %>% group_by(council_name) %>% mutate(pre.post = +(year >= min(year[treat == 1])))

输出

# A tibble: 9 x 4
# Groups:   council_name [3]
council_name  year treat pre.post
<chr>        <int> <int>    <int>
1 Southwark     2008     1        1
2 Southwark     2009     0        1
3 Southwark     2010     1        1
4 Lambeth       2006     0        0
5 Lambeth       2007     1        1
6 Lambeth       2008     0        1
7 Yorkshire     2006     0        0
8 Yorkshire     2007     0        0
9 Yorkshire     2008     0        0
Warning messages:
1: Problem with `mutate()` input `pre.post`.
i no non-missing arguments to min; returning Inf
i Input `pre.post` is `+(year >= min(year[treat == 1]))`.
i The error occurred in group 3: council_name = "Yorkshire". 
2: In min(year[treat == 1]) :
no non-missing arguments to min; returning Inf

当我们将某些内容与设置为Infmin(integer())进行比较时,我们会收到此警告消息。IMO,你可以忽略它,因为这样的比较并没有打破我们的逻辑。

最新更新