如何使用merge()更新R中的表 [英] how to use merge() to update a table in R

查看:102
本文介绍了如何使用merge()更新R中的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何使用merge()来更新数据库.

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

这里是一个例子.以数据框foo

Here is an example. Take for example the 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(),因此顺序很重要

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

这篇关于如何使用merge()更新R中的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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