[英]Retain observations that hasn't occured in the year before in a long time-series dataset in R
我有一個看起來像這樣的df:
ID Year
5 2010
5 2011
5 2014
3 2013
3 2014
10 2013
1 2010
1 2012
1 2014
...
df 包含 2009-2019 年,並針對居住在某個特定城鎮的個人進行過濾,這些人在該特定年份的年齡在 18-64 歲之間。
對於每一年,我只需要保留那一年搬進這個小鎮的人。 因此,例如,我需要保留 2010 年的人口減去 2009 年的人口之間的差異。我還需要每年都這樣做(例如,有些人搬出城幾年,然后return - ID 5 就是一個例子)。 最后,我想要 2010-2019 年的每一年一個 df,所以十個 df 只包含那一年搬進城里的人。
我玩過group_by()
和left_join()
,但沒有成功。 必須有一個簡單的解決方案,但我還沒有找到一個。
您可以使用setdiff
function 來執行 set(A) - set(B) 操作。 按年份將數據拆分為數據框,然后循環遍歷它們,找到新的加入者。
示例代碼:
library(dplyr)
set.seed(123)
df <- tibble(
id = c(1, 2, 3, 4, 5, # first year
1, 2, 3, 5, 6, 7, # 4 moves out, 6,7 move in
2, 3, 4, 6, 7, 8), # 1,5 moves out, 4,8 move in
year = c(rep(2009, 5),
rep(2010, 6),
rep(2011, 6)),
age = sample(18:64, size = 17) # extra column
)
# split into list of dataframes by year
df_by_year <- split(df, df$year)
# create a list to contain the 2 df (total years 3 - 1)
df_list <- vector("list", 2)
for(i in 1:length(df_list)){
# determine incoming new people
new_joinees <- setdiff(df_by_year[[i+1]]$id, df_by_year[[i]]$id)
# filter for above IDs
df_list[[i]] <- dplyr::filter(df_by_year[[i+1]], id %in% new_joinees)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.