R:合并不等的数据帧,并将缺少的行替换为0 [英] R: merge unequal dataframes and replace missing rows with 0

查看:222
本文介绍了R:合并不等的数据帧,并将缺少的行替换为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框架,一个只有字符,另一个字符和值。

  df1 = data 。框架(x = c('a','b','c','d','e'))
df2 = data.frame 'c'),y = c(0,1,0))
合并(df1,df2)
xy
1 a 0
2 b 1
3 c 0

我要合并df1和df2。字符a,b和c合并好,也有0,1,0,但d和e没有。我想要d和e也在合并表中,与0 0条件。因此,对于df2数据帧中的每个缺失行,必须将0置于df1表中,如:

  xy 
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0


解决方案

查看帮助页面进行合并。 all 参数可让您指定不同类型的合并。这里我们要设置 all = TRUE 。这将使不合适值的合并返回 NA ,我们可以使用更新为0 is.na()

  zz<  -  merge(df1,df2,all = TRUE)
zz [ na(zz)]< - 0

> zz
xy
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0


I have two data.frames, one with only characters and the other one with characters and values.

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))
df2 = data.frame(x=c('a', 'b', 'c'),y = c(0,1,0))
merge(df1, df2)
  x y
1 a 0
2 b 1
3 c 0 

I want to merge df1 and df2. The characters a, b and c merged good and also have 0, 1, 0 but d and e has nothing. I want d and e also in the merge table, with the 0 0 condition. Thus for every missing row at the df2 dataframe, the 0 must be placed in the df1 table, like:

  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

解决方案

Take a look at the help page for merge. The all parameter lets you specify different types of merges. Here we want to set all = TRUE. This will make merge return NA for the values that don't match, which we can update to 0 with is.na():

zz <- merge(df1, df2, all = TRUE)
zz[is.na(zz)] <- 0

> zz
  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

这篇关于R:合并不等的数据帧,并将缺少的行替换为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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