【问题标题】:Create a sequence of dates in one data frame based on a second data frame by group基于第二个数据帧按组在一个数据帧中创建日期序列
【发布时间】:2015-09-10 15:33:13
【问题描述】:

我有两个共享一个分组 ID 的数据框。我想根据另一个日期设置的条件创建一个日期序列。 MRE如下:

jdates <- structure(list(Group.1 = c(8, 9), x = structure(c(16674, 16661), class = "Date")), .Names = c("Group.1", "x"), row.names = c(NA, -2L), class = c("data.table", "data.frame"))

jtrying <- structure(list(id = c(8, 8, 8, 9, 9, 9), values1 = 1:6, values2 = 7:12), .Names = c("id", "values1", "values2"), row.names = c(NA, -6L), class = c("data.table", "data.frame"))

在此示例中,我想在 jtrying 中创建一列日期,从 jdates 中的下一个日期开始(每个组 - jdates 中的 Group.1jtrying 中的 id)。

使用 data.table,这些(糟糕的)方法都不起作用:

jtrying[ , date := seq(jdates$x + 1, length.out=3, by = 1), by = jdates$Group.1]

jtrying[ , date := seq(jdates$x + 1, length.out=3, by = 1), by = id]

jtrying[ , date := lapply(.SD,(seq(jdates$x + 1, length.out=3, by = 1))), by = id]

jtrying[ , date := lapply(.SD,function(x) seq(jdates$x + 1, length.out=3, by = 1)), by = id]

我一直在尝试 data.table 方法,因为它们被认为更快(并且真实数据非常大),但实际上,任何事情(在合理范围内)都可以做到。

我的预期结果是一个如下所示的 data.frame:

 jtrying
   id values1 values2       date
1:  8       1       7 2015-08-28
2:  8       2       8 2015-08-29
3:  8       3       9 2015-08-30
4:  9       4      10 2015-08-15
5:  9       5      11 2015-08-16
6:  9       6      12 2015-08-17

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    这就是我要做的事情

    jtrying[jdates, 
      date := seq(from=x+1, by=1, length.out=.N)
    , on=c(id="Group.1"), by=.EACHI]
    

    此语法X[Y, newcol := ..., on=c(Xcol=Ycol), by=.EACHI] 的工作原理如下:

    • XYon 中标识的列上合并。
    • X 为合并列的每个值(即by=.EACHI)分别构建其newcol

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多