r语言 - 将所有缺失的行插入数据表中,以获取 2 列的值范围



我有兴趣将所有缺失的行插入到数据表中,以获得 2 列的新值范围。

例如,dt1[,a]有一些从 1 到 5 的值,就像dt1[,b]一样,但我不仅希望所有成对组合都存在于 a 列和 b 列中,而且所有组合都存在于新定义的范围内,例如 1 到 7 代替。

# Example data.table
dt1 <- data.table(a=c(1,1,1,1,2,2,2,2,3,3,3,4,4,4,4,4,5,5,5),
b=c(1,3,4,5,1,2,3,4,1,2,3,1,2,3,4,5,3,4,5),
c=sample(1:10,19,replace=T))
setkey(dt1,a,b)
# CJ in data.table will create all rows to ensure all
# pair wise combinations are present (using the nominated columns). 
dt1[CJ(a,b,unique=T)]

以上很棒,但只会在提名列中使用最大值和最小值。我希望插入的行为我提供新的指定范围之间的所有组合,例如 1 到 7。将有 49 行。

# the following is a temporary workaround
template <- data.table(a1=rep(1:7,each=7),b1=rep(1:7,7))
setkey(template,a1,b1)
full <- dt1[template]

我们可以将一系列值传递给"a"的"CJ",而不是"a"列中已经存在的值

dt1[CJ(a = 1:7, b, unique = TRUE)]

最新更新