Imagine I have this df
df<-data.frame("A"=c("I","You","She"),"B"=c("kicked","like","saw"),"C"=c("can","dogs","birds"))
and some kind of text block base I want to use for HTML like this (df column names are in the brackets):
"Hello World<br> <b>{A} {B} the {C}.</b>"
I want to get out a list or collection like this:
c("Hello World<br> <b>I Kicked the can.</b>",
"Hello World<br> <b>You like the dogs.</b>",
"Hello World<br> <b>She saw the birds.</b>")
I can imagine iterating over each row of the data.frame, and then using the glue function, but it seems like there should be a short or 1 line solution. Is it possible?
You can use sprintf
and do.call
out <- do.call(sprintf, c(list("Hello World<br> <b>%s %s the %s.</b>"), df))
out
# [1] "Hello World<br> <b>I kicked the can.</b>"
# [2] "Hello World<br> <b>You like the dogs.</b>"
# [3] "Hello World<br> <b>She saw the birds.</b>"
Helpful reference: Can you pass a vector to a vararg?: Vector to sprintf