简体   繁体   English

如何通过匹配R中的一个列值来用另一个数据帧替换数据帧值?

[英]How to replace the data frame value with another data frame by matching one column value in R?

Suppose I have one data frame A like this: 假设我有一个像这样的数据帧A:

index value1 value2
a      ss    aa
b      dd    ff
c      gg    hh
d      yy    zz
e      cc    xx

and another data frame B like this: 另一个像这样的数据帧B:

index value1 value2
c      oooo  pppp
d      uuuu  vvvv

I want A to be replaced by B value and changed to 我希望将A替换为B值并更改为

index value1 value2
a      ss    aa
b      dd    ff
c      oooo  pppp
d      uuuu  vvvv
e      cc    xx

You could do for instance: 您可以例如:

rbind(
  A[!A$index %in% B$index, ],
  merge(A[, "index", drop = FALSE], B)
)
#    index value1 value2
# 1      a     ss     aa
# 2      b     dd     ff
# 5      e     cc     xx
# 11     c   oooo   pppp
# 21     d   uuuu   vvvv

We can do a join on 'index' 我们可以做一个连接on “索引”

library(data.table)
setDT(A)[B, names(A)[-1] := mget(paste0("i.", names(B)[-1])), on = .(index)]
A
#   index value1 value2
#1:     a     ss     aa
#2:     b     dd     ff
#3:     c   oooo   pppp
#4:     d   uuuu   vvvv
#5:     e     cc     xx

NOTE: Assume that the 'value' columns are character and not factor class 注意:假设“值”列是character而不是factor

data 数据

A <- structure(list(index = c("a", "b", "c", "d", "e"), value1 = c("ss", 
"dd", "gg", "yy", "cc"), value2 = c("aa", "ff", "hh", "zz", "xx"
)), .Names = c("index", "value1", "value2"), class = "data.frame", 
 row.names = c(NA, -5L))

B <- structure(list(index = c("c", "d"), value1 = c("oooo", "uuuu"
 ), value2 = c("pppp", "vvvv")), .Names = c("index", "value1", 
"value2"), class = "data.frame", row.names = c(NA, -2L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过匹配来自另一个数据帧的整个列中的字符串来检索一个数据帧中的值? - How to retrieve value in one data frame by matching a string within an entire column from another data frame? 通过匹配 r 中的值和列名,将数据框的值合并到另一个数据框 - Merge values of a data frame to another data frame by matching value and column name in r 将一个数据框中的值替换为另一个 - Replace value in one data frame from another R 中是否有方法将一个数据帧中的值替换为另一个数据帧中的相关值? - Is there method in R to replace values in one data frame with a related value from another data frame? 将值从一个数据帧添加到R中的另一个数据帧 - Add value from one data frame into another data frame in R 将一个数据帧中的列值结果写入r中另一个数据帧中的新列 - writing the results of a column value in one data frame to a new column in another data frame in r R:在数据帧中用一个值替换为另一个值 - R: substituting one value with another in a data frame 如何替换R中数据框中的值? - How to replace a value in a data frame in R? 将一个data.frame的值分配给R中另一个data.frame的特定列? - Assign value from one data.frame to a specific column of another data.frame in R? 如何用另一个值替换数据框中的值 - How to replace values in a data frame with another value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM