我已经使用了 dplyr
和 merge
函数一段时间了,但我刚刚遇到一个我无法弄清楚如何以简单的方式做的任务 . 我想合并两个数据帧 . 第二个数据框缺少一些列 . 我希望merge的输出使用第一个数据帧的相应值填充这些值 .
数据框看起来像这样:
#df1
participant = c(1,2,3)
age = c(18,23,19)
gender = c(rep("female",2),"male")
experiment = rep("noun",3)
rt = c(218,111,546)
df1 = data.frame(participant, age, gender,experiment,rt)
participant age gender experiment rt
1 1 18 female noun 218
2 2 23 female noun 111
3 3 19 male noun 546
#df2
participant = c(1,2,3)
experiment = rep("verb",3)
rt = c(238,251,140)
df2 = data.frame(participant, experiment,rt)
participant experiment rt
1 1 verb 238
2 2 verb 251
3 3 verb 140
这是输出数据框的外观:
participant age gender experiment rt
1 1 18 female noun 218
2 2 23 female noun 111
3 3 19 male noun 546
4 1 18 female verb 238
5 2 23 female verb 251
6 3 19 male verb 140
The goal is that df2
is merged using the column participant , and the values for the columns age and gender 取自 df1
. 我已经尝试了很多东西(所有类型的 join
, rbind.fill
等)我也在论坛中四处寻找,但我找不到一种简单的方法来实现绑定两个数据帧的行并填写缺失的值在 df2
中使用特定列作为参考 . 在我的例子中,只有2列要填写(年龄和性别),但我真正的 df1
还有更多,所以我想避免手工指定它们 .
如果你们中的任何数据合并向导都有建议,我将非常感激!
1 回答
我们将数据集放在
list
中,使用rbindlist
和fill=TRUE
(来自data.table
),按'参与者分组,我们将'age'和'gender'分配(:=
)作为该列中的非NA值 .或者仅使用
base R
,我们rbind
这两个数据集中共有的列子集,然后根据在一个数据集中找到但不在其他数据集中的列创建其他列 .