【发布时间】:2021-03-01 14:47:31
【问题描述】:
我有一个如下所示的数据框 (df):
library(dplyr)
library(lubridate)
id gender education e-week
1 100236 0 Bachelor or equivalent 2012-01-22
2 100237 0 Secondary education 2010-03-14
3 100248 0 Master and doctoral 2010-04-25
4 100257 0 Master and doctoral 2012-01-22
5 100271 0 Bachelor or equivalent 2011-05-22
6 100285 0 Primary education 2012-01-15
7 100303 0 Master and doctoral 2013-01-13
8 100305 0 Secondary education 2011-09-25
9 100316 0 Secondary education 2012-12-30
10 100354 0 Secondary education 2010-08-22
真正的数据集要长得多。我从原始日期得到了“周”变量
df <- df %>%
mutate(., e_week = floor_date(date_exit, unit = "week")
下一步是为从感兴趣的日期开始的不同时间“窗口”创建虚拟变量。首先,我手动创建了它们,如下:
df <- df %>%
mutate(.,treshold_1week =ifelse(e_week %within%
interval(start = as.Date('2009-05-17') - weeks(x = 1),
end = '2009-05-17'),
1, 0 ))
这是在感兴趣日期前 1 周。我在感兴趣的日期之前和之后的 2、3、4、5 和 6 周内手动进行了此操作。现在我想将窗口扩大到感兴趣日期前后的 40 周。有没有更快更有效的方法来做到这一点,而无需为每个虚拟变量编写新的 ifelse() 函数?
我面临的挑战是,我想为接近感兴趣日期的每周创建一个新的虚拟变量。因此,我正在寻找 40 个虚拟变量,它们基本上表示缩短的时间间隔,即
treshold_40weeks、treshold_39weeks、treshold38_weeks 等
【问题讨论】:
-
你读过R标签信息吗?您没有提供任何
library,它实际上是您的代码的一个组件。
标签: r dplyr data-manipulation