Home > other >  Using a function inside gsub in R
Using a function inside gsub in R

Time:12-09

I have

txt <- "{a} is to {b} what {c} is to {d}"
key <- c(a='apple', b='banana', c='chair', d='door')
fun <- function(x) key[x]

and I would like to quickly convert txt according to key into:

"apple is to banana what chair is to door"

I know I can repeatedly use gsub (or similar) like this:

for (v in names(key)) txt <- gsub(sprintf('{%s}',v), fun(v), txt, fixed = TRUE)
txt
# [1] "apple is to banana what chair is to door"

but my txt and key are very long so the above is problematic. I would like to know if there are faster methods like:

gsub('\\{(a|b|c|d)\\}', fun(...), txt, fixed = TRUE) # Does not work

Is it possible? Thanks.

CodePudding user response:

We could use glue after creating the elements of key as objects

list2env(as.list(key), .GlobalEnv)
glue::glue(txt)

-output

apple is to banana what chair is to door

If we don't want to create objects in the global env, an option is also to add the key[ with gsub inside the {} and then use glue

glue::glue(gsub("\\{([^}] )\\}", "{key['\\1']}", txt))
apple is to banana what chair is to door

Or as @Robert Hacken mentioned in the comments, the .envir would be more compact

glue::glue(txt, .envir=as.list(key))
apple is to banana what chair is to door

CodePudding user response:

With mgsub::mgsub:

names(key) <- paste0("\\{", names(key), "\\}")
mgsub::mgsub(txt, names(key), key)
#[1] "apple is to banana what chair is to door"

CodePudding user response:

With glue_data():

library(glue)
glue_data(key, txt)
# apple is to banana what chair is to door
  • Related