R Data Table 用零分配行和列的子集

R Data Table Assign Subset of Rows and Columns with Zero

我试图通过用零值填充未来的时间步长来将数据 table 分解成一个时间序列。起始数据 table 具有以下结构。 V1V2 的值可以被认为是第一个时间步长的值。

dt <- data.table(ID = c(1,2,3), V1 = c(1,2,3), V2 = c(4,5,6))
   ID V1 V2
1:  1  1  4
2:  2  2  5
3:  3  3  6

我要得到的是这样一个数据table

    ID year V1 V2
1:   1    1  1  4
2:   1    2  0  0
3:   1    3  0  0
4:   1    4  0  0
5:   1    5  0  0
6:   2    1  2  5
7:   2    2  0  0
8:   2    3  0  0
9:   2    4  0  0
10:  2    5  0  0
11:  3    1  3  6
12:  3    2  0  0
13:  3    3  0  0
14:  3    4  0  0
15:  3    5  0  0

我分解了原始数据 table 并在 year 列中附加了以下内容

dt <- dt[, .(year=1:5), by=ID][dt, on=ID, allow.cartesian=T]
    ID year V1 V2
 1:  1    1  1  4
 2:  1    2  1  4
 3:  1    3  1  4
 4:  1    4  1  4
 5:  1    5  1  4
 6:  2    1  2  5
 7:  2    2  2  5
 8:  2    3  2  5
 9:  2    4  2  5
10:  2    5  2  5
11:  3    1  3  6
12:  3    2  3  6
13:  3    3  3  6
14:  3    4  3  6
15:  3    5  3  6

任何有关如何为 year!=1 填充零的列 V1V2 的想法将不胜感激。我还需要避免拼出 V1V2 列名称,因为我正在使用的实际数据 table 有 58 列。

我在最后一步中遇到了错误,但是如果您有更新版本的 data.table,它的行为肯定会有所不同 hten:

dt[year != 1, V1 := 0]  # logical condition in the 'i' position
dt[year != 1, V2 := 0]  # data.table assign in the 'j' position

糟糕。没有读到最后。看看我是否可以测试一系列列。

可以在 data.table.[ 赋值运算符 (:=) 的 LHS 上构造范围:

> dt2[year != 1, paste0("V", 1:2) := 0 ]
> dt2
    ID V1 V2 year
 1:  1  1  4    1
 2:  1  0  0    2
 3:  1  0  0    3
 4:  1  0  0    4
 5:  1  0  0    5
 6:  2  2  5    1
 7:  2  0  0    2
 8:  2  0  0    3
 9:  2  0  0    4
10:  2  0  0    5
11:  3  3  6    1
12:  3  0  0    2
13:  3  0  0    3
14:  3  0  0    4
15:  3  0  0    5

你可以使用tidyr::complete-

library(dplyr)
library(tidyr)

dt %>%
  mutate(year = 1) %>%
  complete(ID, year = 1:5, fill = list(V1 = 0, V2 = 0))

#      ID  year    V1    V2
#   <dbl> <dbl> <dbl> <dbl>
# 1     1     1     1     4
# 2     1     2     0     0
# 3     1     3     0     0
# 4     1     4     0     0
# 5     1     5     0     0
# 6     2     1     2     5
# 7     2     2     0     0
# 8     2     3     0     0
# 9     2     4     0     0
#10     2     5     0     0
#11     3     1     3     6
#12     3     2     0     0
#13     3     3     0     0
#14     3     4     0     0
#15     3     5     0     0