[英]Mutate a new column based on lagged values within that column - dplyr approach
[英]Mutate column based on any lagged value of other column in R
我對我認為應該是一個非常簡單的數據轉換任務有一些問題。 我有一個看起來像這樣的 dataframe:
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
的任何較低值處具有值1
,則值為1
用於treat
。 基本上我想要pre.post == 1
如果council
在前year
有過treat == 1
。
這就是我要找的:
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])))
Output
# 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
當我們將某些內容與設置為Inf
的min(integer())
進行比較時,我們會收到此警告消息。 IMO,您可以忽略它,因為這樣的比較不會破壞我們的邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.