根据列值在数据表上动态添加列

时间:2017-12-16 12:21:59

标签: r data.table rows

根据固定的选定值和列定义的值,在data.table中添加序列列的最佳方法是什么。以下示例说明了输入和所需的输出:

library(data.table)

# Input
# Add a column sequence till 7 starting from the value of column V2. 
dt <- data.table(c("A","D","H"), c(2, 4, 5))

# Desired Ouput
dt <- data.table(c(rep("A", 6), rep("D", 4), rep("H", 3)), new_column = c(2:7, 4:7, 5:7))
dt 

1 个答案:

答案 0 :(得分:4)

这是否实现了您的目标?

dt[ , .( new_column = V2:7 ), by = V1 ]

输出:

    V1 new_column
 1:  A          2
 2:  A          3
 3:  A          4
 4:  A          5
 5:  A          6
 6:  A          7
 7:  D          4
 8:  D          5
 9:  D          6
10:  D          7
11:  H          5
12:  H          6
13:  H          7