0

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?

bart cubrich
  • 1,184
  • 1
  • 14
  • 41

1 Answers1

1

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

markus
  • 25,843
  • 5
  • 39
  • 58
  • Is there a way to specify the column name in this? Otherwise it is perfect. I could make a new df, but I would rather not if I can help it. – bart cubrich Jul 19 '20 at 17:10
  • 1
    @bartcubrich A way might be to reorder your `df`, e.g., try `do.call(sprintf, c(list("Hello World
    %s %s the %s."), df[, c("C", "B", "A")]))`
    – markus Jul 19 '20 at 17:15