如何使用merge或replace将R中的表更新为多列 [英] How to use merge or replace to update a table in R with multiple columns
本文介绍了如何使用merge或replace将R中的表更新为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做一些非常类似这个问题:如何使用merge()来更新R 中的表
I want to do something VERY similar to this question: how to use merge() to update a table in R
,但不是只有一列是索引,我想匹配新值
but instead of just one column being the index, I want to match the new values on an arbitrary number of columns >=1.
foo <- data.frame(index1=c('a', 'b', 'b', 'd','e'),index2=c(1, 1, 2, 3, 2), value=c(100,NA, 101, NA, NA))
其中有以下值
foo
index1 index2 value
1 a 1 100
2 b 1 NA
3 b 2 101
4 d 3 NA
5 e 2 NA
以及数据框栏
bar <- data.frame(index1=c('b', 'd'),index2=c(1,3), value=c(200, 201))
其中包含以下值:
bar
index1 index2 value
1 b 1 200
2 d 3 201
merge(foo,bar,by ='index',all = T)
结果是这个输出:
merge(foo, bar, by='index', all=T) It results in this output:
所需输出:
foo
index1 index2 value
1 a 1 100
2 b 1 200
3 b 2 101
4 d 3 201
5 e 2 NA
推荐答案
我认为你不需要合并
,但更多的 rbind
并过滤它们。这里我使用 data.table
来表示糖语法。
I think you don't need a merge
but more to rbind
and filter them later. Here I am using data.table
for sugar syntax.
dx <- rbind(bar,foo)
library(data.table)
setDT(dx)
## note this can be applied to any number of index
setkeyv(dx,grep("index",names(dx),v=T))
## using unqiue to remove all duplicated
## here it will remove the duplicated with missing values which is the
## expected behavior
unique(dx)
# index1 index2 value
# 1: b 1 200
# 2: b 2 101
# 3: d 3 201
# 4: a 1 100
# 5: e 2 NA
您可以更明确,并按索引组过滤您的行:
you can be more explicit and filter your rows by group of indexs:
dx[,ifelse(length(value)>1,value[!is.na(value)],value),key(dx)]
这篇关于如何使用merge或replace将R中的表更新为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文