我有这个df。我想根据查找表替换"1.1“、"2.1”、"3.2“等的每个实例。
查找表
期望输出
我看了看Replace values in a dataframe based on lookup table,它不能解决我的问题。提前感谢!
发布于 2019-05-24 03:03:10
一个选项是gsubfn
。我们以点([0-9.]+
)作为模式匹配一个或多个数字,并在替换中传递从第二个数据集('df2')创建的键/值对的list
。对于具有“key”的匹配模式,它将替换字符串中相应的“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)
https://stackoverflow.com/questions/56281390
复制相似问题