gpt4 book ai didi

R:如何按列名合并2个数据框

转载 作者:行者123 更新时间:2023-12-05 01:01:27 30 4
gpt4 key购买 nike

apple = data.frame(Obs = c(1:4), Color = c("red", "red", "red", "green"), Weight = c(1.1, 1.2, 1.3, 1.4))
orange = data.frame(Obs = c(1:6), Weight = c(2, 3, 4, 5, 6, 7))

我有两个 data.frames,appleorange,其中后者的列是前者的子集。

> apple
Obs Color Weight
1 1 red 1.1
2 2 red 1.2
3 3 red 1.3
4 4 green 1.4
> orange
Obs Weight
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
6 6 7

我想合并 2 个 data.frames,结果应该是这样的:

> apple_orange
Obs Color Weight
1 1 red 1.1
2 2 red 1.2
3 3 red 1.3
4 4 green 1.4
5 1 NA 2
6 2 NA 3
7 3 NA 4
8 4 NA 5
9 5 NA 6
10 6 NA 7

有什么方法可以合并它以使我没有指定特定的列名? IE。我的实际数据集共有数百列,所以我不想一一输入。

最佳答案

您可以使用 dplyr::bind_rows 按名称匹配列并用 NA 填充缺失的列,这里是文档:

When row-binding, columns are matched by name, and any values that don't match will be filled with NA.

dplyr::bind_rows(apple, orange)

Obs Color Weight
1 1 red 1.1
2 2 red 1.2
3 3 red 1.3
4 4 green 1.4
5 1 <NA> 2.0
6 2 <NA> 3.0
7 3 <NA> 4.0
8 4 <NA> 5.0
9 5 <NA> 6.0
10 6 <NA> 7.0

关于R:如何按列名合并2个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44271328/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com