1

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

enter image description here

Lookup table

enter image description here

Desired output

enter image description here

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

Ketty
  • 811
  • 10
  • 21

1 Answers1

2

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)
akrun
  • 874,273
  • 37
  • 540
  • 662