【问题标题】:Combining two dataframes together to create a long dataframe with all combinations [duplicate]将两个数据框组合在一起以创建具有所有组合的长数据框[重复]
【发布时间】:2021-08-09 12:10:49
【问题描述】:

我希望(我认为)在 R(或 python,但我目前在 R 中工作)中将两个数据帧融合在一起。由于不知道问题的正确措辞,我可能一直在寻找所有错误的角落,但仍然找不到答案。

我有两个大小不同的数据帧(datA、datB),我需要将它们组合在一起以创建一个“长”数据帧 - datC。

datA <- data.frame("Val1" = c(1, 2, 3),
              "Val2" = c(0,1,1))


datB <- data.frame("Val3" = c("A","B","C","D"),
              "Val4" = c(15,25,35,45))

我希望将这些数据帧合并到 datC 中,我不介意 datC 是从 datA 还是 datB 创建的,因为一旦我有了最终数据集,这些数据帧就会被删除。

datC 应如下所示:

datC <- data.frame("Val1" = c(1,1,1,1,2,2,2,2,3,3,3,3),
              "Val2" = c("A","B","C","D","A","B","C","D","A","B","C","D"),
              "Val3" = c(0,0,0,0,1,1,1,1,1,1,1,1),
              "Val4" = c(15,25,35,45,15,25,35,45,15,25,35,45))
Val1       Val2       Val3       Val4
1          A          0          15
1          B          0          25
1          C          0          35
1          D          0          45
2          A          1          15
2          B          1          25
2          C          1          35
2          D          1          45
3          A          1          15
3          B          1          25
3          C          1          35
3          D          1          45

正如我所说,我不知道我的问题到底该怎么称呼,所以寻找解决方案一直是一个挑战。一旦我知道我在寻找什么,我会更改标题以帮助其他人。

编辑:下面的答案适用 merge(datA, datB, all=TRUE),

这个问题已经有人问过了,看这个帖子:combine two data frames with all posible combinations

我不知道这是否意味着该帖子已被关闭,但如果没有,我不会删除它,因为它可能会帮助像我一样不知道要搜索什么的其他人。

非常感谢您的快速帮助

【问题讨论】:

  • tidyr::crossing(datA, datB)

标签: r dataframe


【解决方案1】:

它被称为交叉连接(或笛卡尔积),可以在基础 R 中轻松完成

merge(datA,datB,all=TRUE)

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2014-08-17
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多