复制data.table中每个组的最后一行并更改一列的值

时间:2017-09-01 15:28:43

标签: r dplyr data.table

我有 // bound to list items on front end, reacts to tap on each item // and loads route information for the route that is selected RouteInfo _selected_item; public RouteInfo RouteLabelSelected { get { return _selected_item; } set { if (Equals(value, _selected_item)) return; _selected_item = value; OnPropertyChanged(nameof(RouteLabelSelected)); OpenRoutePage(_selected_item.ID); } } ,如下所示:

data.table

我想在每个组的末尾(通过ID)插入一行,除了日期之外,它与最后一行相同,除了最后一次观察之外应该比一个月多一个月:

    ID Date        v3  v4
     1 2015.01.01   a   5
     1 2015.02.01   b   5
     1 2015.03.01   f   1
     1 2015.04.01   z   5
     1 2015.05.01   a   2
     2 2013.03.01   a   6
     2 2013.04.01   a   2
     2 2013.05.01   g  13
     2 2013.06.01   a   2
     2 2013.07.01   e   8
     2 2013.08.01   h   9
     2 2013.09.01   h   9

提前谢谢!

1 个答案:

答案 0 :(得分:1)

我们可以使用数据集

提取最后一行和rbind
library(data.table)
library(lubridate)
rbind(setDT(df1), df1[, Date := as.Date(Date, "%Y.%m.%d")][,
       .SD[.N], ID][, Date := Date %m+% months(1)])[order(ID)]
#    ID       Date v3 v4
# 1:  1 2015-01-01  a  5
# 2:  1 2015-02-01  b  5
# 3:  1 2015-03-01  f  1
# 4:  1 2015-04-01  z  5
# 5:  1 2015-05-01  a  2
# 6:  1 2015-06-01  a  2
# 7:  2 2013-03-01  a  6
# 8:  2 2013-04-01  a  2
# 9:  2 2013-05-01  g 13
#10:  2 2013-06-01  a  2
#11:  2 2013-07-01  e  8
#12:  2 2013-08-01  h  9
#13:  2 2013-09-01  h  9
#14:  2 2013-10-01  h  9

注意:将“日期”转换为Date

可能更好

或者@Frank提到,来自seq.Date的{​​{1}}可以用来获取'月'的序列

base R