我想将df1$colB
的值替换为df2$replacement
中df1$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循环解决方案。
答案 0 :(得分:3)
您可以在merge
和df1
上执行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,函数
翻译角色向量中的字符