R data.table按组创建列表列

时间:2018-11-21 15:55:44

标签: r data.table

我下面有一个data.table,我想将一个函数应用于按v2v1分组的order列,结果列v3应该是下面的向量列表。

如何编写此函数,以便为每个组的第一行(order == 1 & v1 %in% c(1, 2))返回0的向量。对于组中的每个后续行,向量将在向量的右边附加上一行的v2值,同时从左边碰掉一个0

初始data.table

t3 <- data.table(
  v1 = rep(1:2, each = 5),
  order = rep(1:5, 2),
  v2 = c(6, 9, 6, 8, 6, 2, 5, 7, 8, 2)
)

    v1 order v2
 1:  1     1  6
 2:  1     2  9
 3:  1     3  6
 4:  1     4  8
 5:  1     5  6
 6:  2     1  2
 7:  2     2  5
 8:  2     3  7
 9:  2     4  8
10:  2     5  2

正在应用功能...

输出:

t3[, v3 := list(c(0, 0, 0, 0, 0),
                c(0, 0, 0, 0, 6),
                c(0, 0, 0, 6, 9),
                c(0, 0, 6, 9, 6),
                c(0, 6, 9, 6, 8),
                c(0, 0, 0, 0, 0),
                c(0, 0, 0, 0, 2),
                c(0, 0, 0, 2, 5),
                c(0, 0, 2, 5, 7),
                c(0, 2, 5, 7, 8))]

    v1 order v2        v3
 1:  1     1  6 0,0,0,0,0
 2:  1     2  9 0,0,0,0,6
 3:  1     3  6 0,0,0,6,9
 4:  1     4  8 0,0,6,9,6
 5:  1     5  6 0,6,9,6,8
 6:  2     1  2 0,0,0,0,0
 7:  2     2  5 0,0,0,0,2
 8:  2     3  7 0,0,0,2,5
 9:  2     4  8 0,0,2,5,7
10:  2     5  2 0,2,5,7,8

1 个答案:

答案 0 :(得分:2)

我们可以尝试

t3[order(order), .(order, v2, shift(v2, 5:1, fill = 0)), by = v1]

输出:

    v1 order v2        V3
 1:  1     1  6 0,0,0,0,0
 2:  1     2  9 0,0,0,0,6
 3:  1     3  6 0,0,0,6,9
 4:  1     4  8 0,0,6,9,6
 5:  1     5  6 0,6,9,6,8
 6:  2     1  2 0,0,0,0,0
 7:  2     2  5 0,0,0,0,2
 8:  2     3  7 0,0,0,2,5
 9:  2     4  8 0,0,2,5,7
10:  2     5  2 0,2,5,7,8