【问题标题】:R data.table create from all combinations of multiple data.tables [duplicate]R data.table从多个data.tables的所有组合创建[重复]
【发布时间】:2020-01-30 12:06:08
【问题描述】:

我有:

require(data.table)

tblDT1 <- data.table(ID_1 = 1:2)     # in reality, there are multiple columns per table
tblDT2 <- data.table(ID_2 = 3:4)
tblDT3 <- data.table(ID_3 = 5:6)

tblDT1
tblDT2
tblDT3

我想创建一个新的data.table,它是来自多个输入的所有行的组合:

resultDT <- data.table(ID_1 = rep(1:2, each = 4),
                       ID_2 = rep(3:4, times = 4),
                       ID_3 = rep(5:6, times = 2, each = 2))
resultDT
   ID_1 ID_2 ID_3
1:    1    3    5
2:    1    4    5
3:    1    3    6
4:    1    4    6
5:    2    3    5
6:    2    4    5
7:    2    3    6
8:    2    4    6
  • 我拥有的每个 data.table 中的行数和/或列数不同。

这样做的正确和有效方法是什么?

我已经尝试过expand.grid, merge,但它们不适用于我的情况。

请注意,实际上我在每个 data.table 输入中都有 多个列,因此通过显式调用 CJ or expand.grid 中的所有列名,例如CJ(DT1$col1, DT1$col2, DT2$col3...) 不太理想。

【问题讨论】:

标签: r join merge data.table expand


【解决方案1】:

我们可以使用tidyr::crossing

tidyr::crossing(tblDT1, tblDT2, tblDT3)

#   ID_1  ID_2  ID_3
#  <int> <int> <int>
#1     1     3     5
#2     1     3     6
#3     1     4     5
#4     1     4     6
#5     2     3     5
#6     2     3     6
#7     2     4     5
#8     2     4     6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 2021-03-24
    • 1970-01-01
    • 2018-06-08
    • 2020-12-23
    • 2021-03-06
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多