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

这一生的挚爱 提交于 2019-12-11 08:44:33

问题


I have this df. I'd like to replace every instance of "1.1", "2.1" "3.2", etc. based on a lookup table.

Lookup table

Desired output

I looked at Replace values in a dataframe based on lookup table it doesn't solve my problem. Thanks in advance!


回答1:


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"

data

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/how-to-replace-string-values-in-a-column-based-on-a-lookup-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!