从不同的data.frame添加缺少的列填充为0 [英] Add missing columns from different data.frame filled with 0

查看:86
本文介绍了从不同的data.frame添加缺少的列填充为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

df1
a b c d
1 2 3 4

df2
a c
5 6

我想要的结果是,以使用df1中缺少的列填充第二个data.frame并将它们填充为零。因此结果应该是:

And the result I want is, to fill up the second data.frame with the missing columns from df1 and fill them with zeros. So the result should be:

df3
a b c d
5 0 6 0

数据框非常大,这就是为什么自动做到这一点的原因。

The Data frames are quite big and that is why an automated way of doing this would be gerate.

推荐答案

我们可以使用 setdiff 来查找 df2中不存在的列并将值0分配给这些列。

We can use setdiff to find out columns which are not present in df2 and assign the value 0 to those columns.

df2[setdiff(names(df1), names(df2))] <- 0

#  a c b d
#1 5 6 0 0

如果我们想保持与 df1 相同的列顺序,我们以后可以做

If we want to maintain the same order of columns as in df1 we can later do

df2[names(df1)]
#  a b c d
#1 5 0 6 0

这篇关于从不同的data.frame添加缺少的列填充为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆