3

Imagine I have the following function which has a lot of arguments but for the sake of simplicity I only list two here:

library(glue)
glue("{a} + {b} is equal to 3", a = 1, b = 2)

Now I have a data.table with all the arguments/values that I want to pass to my glue function: data.table:

library(data.table)
DT <- data.table(varnames = c("a", "b"), values = c(1, 2))

How could I directly pass the arguments/values from my DT onto my glue function?

4 Answers 4

1

You can use setNames and call glue_data:

glue_data(setNames(DT$values, DT$varnames), "{a} + {b} is equal to 3")
#1 + 2 is equal to 3

or you use do.call:

do.call(glue, as.list(c("{a} + {b} is equal to 3",
    setNames(DT$values, DT$varnames))))
#1 + 2 is equal to 3
Sign up to request clarification or add additional context in comments.

Comments

1

It would be helpful in this case if you had a and b as separate columns.

library(data.table)
library(glue)

DT_Wide <- dcast(DT, rowid(varnames)~varnames, value.var = 'values')
DT_Wide

#   varnames a b
#1:        1 1 2

Then you can use glue_data -

glue_data(DT_Wide, "{a} + {b} is equal to 3")

#1 + 2 is equal to 3

Comments

1

I would keep it simple and use base R's with as this is the nice example where it is useful:

library(glue)
library(data.table)
DT = data.table(varnames = c("a", "b"), values = c(1, 2))
with(
  as.list(setNames(DT$values, DT$varnames)),
  glue("{a} + {b} is equal to 3")
)
#1 + 2 is equal to 3

Comments

0

A little hackish but gets the job done and generalises to a bigger data.frame:

DT <- data.table(varnames = c("a", "b", "c"), values = c(1, 2, 3))
DT[, glue_data(
       setNames(values, varnames),  
       glue_data(
         .SD,
         "{paste(sprintf('{%s}', varnames), collapse = ' + ')}", " is equal to {sum(values)}"
       )
     )]
# 1 + 2 + 3 is equal to 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.