使用 merge() 使用来自第二个数据框的值更新数据框 [英] Use merge() to update a data frame with values from a second data frame

查看:23
本文介绍了使用 merge() 使用来自第二个数据框的值更新数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何使用 merge() 来更新数据框.

I'm trying to figure out how to use merge() to update a data frame.

以数据框foo

foo <- data.frame(index=c('a', 'b', 'c', 'd'), value=c(100, 101, NA, NA))

具有以下值

index value
1     a   100
2     b   101
3     c    NA
4     d    NA

和数据框bar

bar <- data.frame(index=c('c', 'd'), value=c(200, 201))

具有以下值:

 index value
1     c   200
2     d   201

当我运行以下 merge() 函数来更新 cd

When I run the following merge() function to update the values for c and d

merge(foo, bar, by='index', all=T)

结果如下:

 index value.x value.y
1     a     100      NA
2     b     101      NA
3     c      NA     200
4     d      NA     201

我希望 merge() 的输出避免在此特定示例中创建 value.xvalue.y 但只保留 value 的原始列 有没有简单的方法可以做到这一点?

I'd like the output of merge() to avoid the creation of, in this specific example, of value.x and value.y but only retain the original column of value Is there a simple way of doing this?

推荐答案

merge() 不是总是将列绑定在一起吗?replace() 有效吗?

Doesn't merge() always bind columns together? Does replace() work?

foo$value <- replace(foo$value, foo$index %in% bar$index, bar$value)

match() 所以顺序很重要

or match() so the order matters

foo$value[match(bar$index, foo$index)] <- bar$value

这篇关于使用 merge() 使用来自第二个数据框的值更新数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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