【问题标题】:How to merge a row from dataframe into another when they have unequal number of columns and only insert columns which match当它们具有不相等的列数并且仅插入匹配的列时,如何将数据框中的行合并到另一个中
【发布时间】:2026-02-16 22:35:01
【问题描述】:

我有两个 df,看起来像:

>df1
name   time    date
Dan    01:00    Apr-17
Ann    02:00    Apr-17

>df2
name   time
Joe    03:00
Bob    04:00

>out
name   time
Dan    01:00
Ann    02:00
Joe    03:00

我想在不创建新列的情况下将 df1 中的一行合并到 df2 中。此外,names 下的数据是行名,不应被覆盖。我的实际数据框分别有 ~800 和 99 列。

我在之前的类似问题中尝试过以下答案,但我无法得到我想要的结果,包括 rbind、bind_rows、rbind.fill。这些在某种程度上有效,但总是删除我的行名

rbind.fill(df1, df2[colnames(df2) %in% colnames(df2)])
rbind(df2, df1[1,names(df1)])
bind_rows(df1[1,], df2)

【问题讨论】:

  • rbind.fill 不是基本 R 函数。请在代码中包含您正在使用的任何包的名称。

标签: r dataframe data-binding


【解决方案1】:

你的尝试非常接近。

rbind.fill(df1, df2[colnames(df2) %in% colnames(df2)])

基本上说:将 df1 绑定到 df2,但只取 df2 中也在 df2 中的列。

但这不是你想要做的。试试:

rbind(df1[colnames(df1) %in% colnames(df2)], df2)

其中说: 将 df1 绑定到 df2,但只取 df1 中也在 df2 中的列。

结果:

  name  time
1  Dan 01:00
2  Ann 02:00
3  Joe 03:00
4  Bob 04:00

或者只添加来自 df2 的行,其中 name=="Joe"

rbind(df1[colnames(df1) %in% colnames(df2)], df2[df2$name=="Joe",])

结果:

  name  time
1  Dan 01:00
2  Ann 02:00
3  Joe 03:00

【讨论】:

  • 谢谢弗洛里安。有没有办法指定 df2 中的特定行与 df1 合并?
  • 我不太确定你的意思。输出似乎与您请求的输出相匹配?
  • 它的诀窍已经足够了。我只是在包含特定行时遇到困难,我希望将其强制转换为 df2。
  • 我试过这些,我得到以下错误i evaluates to a logical vector length 845 but there are 112 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.
  • 我修改了我的答案以展示如何做到这一点。确保您不会意外执行df2[df1$name=="Joe",],您的错误听起来可能是问题所在。否则考虑为该特定问题打开一个新问题,请查看here
【解决方案2】:

这是一个使用tidyverse的选项

library(tidyverse)
bind_rows(df1[-3], df2)
#   name  time
#1  Dan 01:00
#2  Ann 02:00
#3  Joe 03:00
#4  Bob 04:00

【讨论】:

    最近更新 更多