Search code examples
rstringpattern-matchinggsubfn

How to replace string patterns with some numbers using gsubfn


I have a dataset df1.

enter image description here

I'd like to replace each occurence of "One + one," "Two ; one," etc. with some numbers as shown in the lookup table df2.

enter image description here

Desired output:

enter image description here

Any idea how to do this? This is a follow-up to my original question How to replace string values in a column based on a lookup table

I tried the following but it doesn't work. Thanks in advance!

 df1$New <- gsubfn::gsubfn("[A-z]+,;", as.list(setNames(df2$Node,df2$Label)), df1$Node)

Data:

df1 <- data.frame(ID = 1:5, Node = c("One + one > Two ; one > Three ; two", "One + two > Two ; two > Three ; one", "One + one > Two ; two > Three ; one", "One + two > Two ; one > Three ; two", "One + one > Two ; two > Three ; two"), 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)

UPDATED DATA:

df1 <- data.frame(ID = 1:5, Node = c("AO Ales + Bitter > Brown and Stout > Premium && Super Premium", "Lager > Dry, Premium Strength, Style, Traditional > Mainstream & Value", "AO Ales + Bitter > Dry, Premium Strength, Style, Traditional > Mainstream & Value", "Lager > Brown and Stout > Dry, Premium Strength, Style, Traditional", "AO Ales + Bitter > Dry, Premium Strength, Style, Traditional > Premium && Super Premium"), stringsAsFactors = FALSE)

df2 <- data.frame(Label = c("AO Ales + Bitter", + "Lager", + "Brown and Stout", + "Dry, Premium Strength, Style, Traditional", + "Mainstream & Value", + "Premium && Super Premium" + ), Node = c("1.1", "1.2", "2.1", "2.2", "3.1", "3.2"), stringsAsFactors = FALSE)


Solution

  • We can do this more easily

    library(gsubfn)
    library(english)
    gsubfn("([a-z]+)", as.list(setNames(1:9, as.character(as.english(1:9)))), 
                    tolower(gsub("\\s*[+;]\\s*", ".", df1$Node)))
    #[1] "1.1 > 2.1 > 3.2" "1.2 > 2.2 > 3.1" "1.1 > 2.2 > 3.1" 
    #[4] "1.2 > 2.1 > 3.2" "1.1 > 2.2 > 3.2"
    

    Update

    Based on the new example, we can do this in base R

    nm1 <- setNames(df2$Node, df2$Label)
    sapply(strsplit(df1$Node, " > "), function(x) paste(nm1[x], collapse = " > "))
    #[1] "1.1 > 2.1 > 3.2" "1.2 > 2.2 > 3.1" "1.1 > 2.2 > 3.1" 
    #[4] "1.2 > 2.1 > 2.2" "1.1 > 2.2 > 3.2"