如何根据查找表替换列中的字符串值 [英] How to replace string values in a column based on a lookup table
本文介绍了如何根据查找表替换列中的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个df.我想根据查找表替换"1.1","2.1","3.2"等的每个实例.
I have this df. I'd like to replace every instance of "1.1", "2.1" "3.2", etc. based on a lookup table.
查询表
所需的输出
我查看了替换数据框中的值基于查找表不能解决我的问题. 预先感谢!
I looked at Replace values in a dataframe based on lookup table it doesn't solve my problem. Thanks in advance!
推荐答案
选项为gsubfn
.我们将一个或多个数字与一个点([0-9.]+
)匹配为模式,并在替换中传递从第二个数据集('df2')创建的键/值对的list
.对于带有键"的匹配模式,它将替换字符串中相应的值"
An option would be gsubfn
. We match one or more digits with a dot ([0-9.]+
) as the pattern and in the replacement, pass a list
of key/value pairs created from the second dataset ('df2'). For the matching pattern with the 'keys', it replace the corresponding 'value' within the string
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)
这篇关于如何根据查找表替换列中的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文