Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a function inside gsub in R

Tags:

string

r

gsub

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 something 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(sprintf('{%s}',names(key)), key, fixed = TRUE) # Does not work
gsub('\\{(a|b|c|d)\\}', fun(...), txt, fixed = TRUE) # Does not work

Is it possible? Thanks.

like image 886
chan1142 Avatar asked Aug 25 '26 22:08

chan1142


1 Answers

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
like image 147
akrun Avatar answered Aug 27 '26 17:08

akrun