我有一个数据集如下
Id Date1
121 2011-01-03
121 2011-01-03
121 2011-04-02
121 2011-08-14
121 2012-01-14
121 2012-05-12
975 2011-02-01
975 2011-02-01
975 2011-06-14
975 2012-01-06
975 2012-04-19
975 2012-09-25
我想要创建的是如下所示的输出,其中新的Date2列根据id偏移一个值,
Id Date1 Date2
121 2011-01-03 2011-01-03
121 2011-01-03 2011-04-02
121 2011-04-02 2011-08-14
121 2011-08-14 2012-01-14
121 2012-01-14 2012-05-12
121 2012-05-12 NA
975 2011-02-01 2011-02-01
975 2011-02-01 2011-06-14
975 2011-06-14 2012-01-06
975 2012-01-06 2012-04-19
975 2012-04-19 2012-09-25
975 2012-09-25 NA
Id 121的Date2列第2行,即2011-01-03变为Date1列,Id112的第1行值。
ID 121的Date2列row3,即2011-04-02变为Date1列,Id 121的row2值....所以......这应该由id发生。
感谢任何帮助。
答案 0 :(得分:2)
使用dplyr
,我们可以按“ID&ID”分组。并创建一个新列' Date2'使用mutate
和lead
library(dplyr)
df1 %>%
group_by(Id) %>%
mutate(Date2= lead(Date1))
# Id Date1 Date2
#1 121 2011-01-03 2011-01-03
#2 121 2011-01-03 2011-04-02
#3 121 2011-04-02 2011-08-14
#4 121 2011-08-14 2012-01-14
#5 121 2012-01-14 2012-05-12
#6 121 2012-05-12 NA
#7 975 2011-02-01 2011-02-01
#8 975 2011-02-01 2011-06-14
#9 975 2011-06-14 2012-01-06
#10 975 2012-01-06 2012-04-19
#11 975 2012-04-19 2012-09-25
#12 975 2012-09-25 NA
或者使用devel版data.table
的类似选项会转换' data.frame'到' data.table' (setDT(df1)
),按' Id'分组,并使用shift
功能选项type='lead'
library(data.table)#v1.9.5+
setDT(df1)[, Date2:= shift(Date1, type='lead') , by = Id][]
# Id Date1 Date2
# 1: 121 2011-01-03 2011-01-03
# 2: 121 2011-01-03 2011-04-02
# 3: 121 2011-04-02 2011-08-14
# 4: 121 2011-08-14 2012-01-14
# 5: 121 2012-01-14 2012-05-12
# 6: 121 2012-05-12 NA
# 7: 975 2011-02-01 2011-02-01
# 8: 975 2011-02-01 2011-06-14
# 9: 975 2011-06-14 2012-01-06
#10: 975 2012-01-06 2012-04-19
#11: 975 2012-04-19 2012-09-25
#12: 975 2012-09-25 NA
或者我们可以使用ave
中的base R
。我们按照“Id'列,删除第一个观察结果并在最后与NA
连接。
df1$Date2 <- with(df1, ave(Date1, Id, FUN=function(x) c(x[-1], NA)))