当第二个数据帧中存在匹配值时,替换数据帧列的值

时间:2016-05-24 12:33:38

标签: r

我想将df1$colB的值替换为df2$replacementdf1$colB等于df2$matches的值。

df1 <- data.frame(colA = 1:10, colB = letters[1:10])

df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1])

结果应该看起来像df3

df3 <- data.frame(colA =1:10, colB = c(LETTERS[1:4],letters[5:10]))

我想避免执行此任务的for循环解决方案。

2 个答案:

答案 0 :(得分:3)

您可以在mergedf1上执行df2,然后将colB值替换为replacement

library(dplyr)
merge(df1, df2, by.x = "colB", by.y = "matches", all.x = T) %>% 
  mutate(colB = ifelse(!is.na(replacement), replacement, colB)) %>%  
  select(colA, colB)
   colA colB
1     1    A
2     2    B
3     3    C
4     4    D
5     5    e
6     6    f
7     7    g
8     8    h
9     9    i
10   10    j

答案 1 :(得分:3)

您可以使用基础R中的chartr功能。

# read in data with character vectors, not factors
df1 <- data.frame(colA = 1:10, colB = letters[1:10], stringsAsFactors=F)
df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1], stringsAsFactors=F)
df3 <- data.frame(colA =1:10, colB = c(LETTERS[1:4],letters[5:10]), stringsAsFactors=F)

# replace the characters with the desired characters
df1$colB <- chartr(paste(df2$matches, collapse=""), 
                   paste(df2$replacement, collapse=""), df1$colB)

根据帮助文件,`?chartr,函数

  

翻译角色向量中的字符