Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a table as function parameters and values

Tags:

r

data.table

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?

like image 497
mat Avatar asked Mar 22 '26 05:03

mat


1 Answers

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
like image 99
GKi Avatar answered Mar 23 '26 19:03

GKi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!