如何找到&根据另一个表中的值替换表中的值

时间:2016-05-09 01:08:22

标签: r

我想找到&如果匹配DF1 $ group = DF2 $ group

,则将DF1 $ Value中的值替换为DF1 $ Value
DF1
group       Value
12357      ABC D
12575      GHI JK
19718      LMN O
19716      LMN OP
18947      QR S TV

DF2
group       Value
12357      ABCD
12575      GHIJK
19718      LMNO
18947      QR STV

我怎样才能在R中写这个语句? 提前致谢

4 个答案:

答案 0 :(得分:2)

以下是包含dplyr包的解决方案,您可能需要将值列从因子转换为字符。

library(dplyr)
DF1$Value <- as.character(DF1$Value)
DF2$Value <- as.character(DF2$Value)
merge(DF1, DF2, by = "group", all.x = T) %>% 
      mutate(Value = ifelse(!is.na(Value.y), Value.y, Value.x)) %>% 
      select(group, Value)

  group        Value
1 12357         ABCD
2 12575        GHIJK
3 18947       QR STV
4 19716       LMN OP
5 19718         LMNO

答案 1 :(得分:2)

当然是data.table解决方案

library(data.table)

setDT(DF1)
setDT(DF2)

DF1[ DF2, on = c("group"), Value := i.Value]
## here the 'Value' of DF1 is being updated with the 'Value' of DF2
## where there is a common 'group' value between the two tables.    

DF1
   group  Value
1: 12357   ABCD
2: 12575  GHIJK
3: 19718   LMNO
4: 19716 LMN OP
5: 18947 QR STV

答案 2 :(得分:1)

以下是base R选项match

 i1 <- with(DF1, match(group, DF2$group))
 DF1$Value <- with(DF1, ifelse(is.na(i1), Value, DF2$Value[i1]))
 DF1
 #  group  Value
 #1 12357   ABCD
 #2 12575  GHIJK
 #3 19718   LMNO
 #4 19716 LMN OP
 #5 18947 QR STV

答案 3 :(得分:1)

以下是使用merge的基本解决方案:

transform(merge(df1,df2, by='group', all.x=TRUE), 
          Value = ifelse(is.na(Value.y), Value.x, Value.y)
)[c('group','Value')]
##   group  Value
## 1 12357   ABCD
## 2 12575  GHIJK
## 3 18947 QR STV
## 4 19716 LMN OP
## 5 19718   LMNO

这假设您在characterdf1中拥有df2个值。否则,您需要使用Value.x包裹Value.yas.character

... ifelse(is.na(Value.y), as.character(Value.x), as.character(Value.y)) ...