这是一种使用gsub
另一种模式替换向量中的特定模式的方法。如果有任何问题,请随时提问!
# Sample data
df1 <- data.frame(Orig = c("AAA", "BBB", "CCC", "DDD", "EEE"),
Replacefor = c(111, 222, 333, 444, 555))
df2 <- data.frame(id = c("AAAXXX", "BBBXXX", "CCCXXX", "DDDXXX", "EEEXXX"),
amount = c(5, 13, 21, 22, 8))
# Pattern replacement
df2[, 1] <- sapply(1:nrow(df1), function(i) {
# Row in df2 that matches pattern from column 1 of df1, e.g. "AAA"
tmp.row <- grep(df1[i, 1], substr(df2[, 1], 1, 3))
# Replace pattern with content from column 2 of df1, e.g. "111"
paste(gsub(df1[i, 1], df1[i, 2], substr(df2[tmp.row, 1], 1, 3)), substr(df2[tmp.row, 1], 4, 6), sep = "")
})
df2
id amount
1 111XXX 5
2 222XXX 13
3 333XXX 21
4 444XXX 22
5 555XXX 8