0

想象一下我有这个df

df<-data.frame("A"=c("I","You","She"),"B"=c("kicked","like","saw"),"C"=c("can","dogs","birds"))

以及我想用于这样的 HTML 的某种文本块基础(df 列名在括号中):

"Hello World<br> <b>{A} {B} the {C}.</b>"

我想得到一个这样的列表或集合:

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>")

我可以想象遍历 data.frame 的每一行,然后使用胶水函数,但似乎应该有一个简短的或 1 行的解决方案。可能吗?

4

1 回答 1

1

您可以使用sprintfdo.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>"

有用的参考:你可以将向量传递给可变参数吗?:向量到 sprintf

于 2020-07-19T16:54:25.870 回答