如何根据查找替换列中的字符串值 table

How to replace string values in a column based on a lookup table

我有这个df。我想根据查找 table.

替换“1.1”、“2.1”、“3.2”等的每个实例

查找table

期望的输出

我查看了 它并没有解决我的问题。 提前致谢!

一个选项是gsubfn。我们将一个或多个数字与一个点 ([0-9.]+) 匹配作为模式,并在替换中传递从第二个数据集 ('df2') 创建的 key/value 对中的 list .对于'keys'的匹配模式,将字符串

中对应的'value'替换掉
library(gsubfn)
df1$Node <- gsubfn("([0-9.]+)", as.list(setNames(df2$Label,df2$Node)), df1$Node)
df1$Node
#[1] "One one > Two one > Three two" "One two > Two two > Three one" "One one > Two two > Three one" "One two > Two one > Three two"
#[5] "One one > Two two > Three two"

数据

df1 <- data.frame(ID = 1:5, Node = c("1.1 > 2.1 > 3.2", "1.2 > 2.2 > 3.1", "1.1 > 2.2 > 3.1", "1.2 > 2.1 > 3.2", "1.1 > 2.2 > 3.2"), stringsAsFactors = FALSE)

df2 <- data.frame(Label =  c("One one", "One two", "Two one", "Two two", "Three one", "Three two"), Node = c("1.1", "1.2", "2.1", "2.2", "3.1", "3.2"), stringsAsFactors = FALSE)