繁体   English   中英

如何基于查找表替换列中的字符串值

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

我有这个df。 我想根据查找表替换“ 1.1”,“ 2.1”,“ 3.2”等的每个实例。

在此处输入图片说明

查找表

在此处输入图片说明

所需的输出

在此处输入图片说明

我查看了基于查找表的数据框中的替换值,但不能解决我的问题。 提前致谢!

一个选项是gsubfn 我们将一个或多个数字与一个点( [0-9.]+ )进行匹配,并在替换中传递从第二个数据集('df2')创建的键/值对list 对于带有“键”的匹配模式,它将替换字符串中相应的“值”

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM