如何从 r 中的 data.frame 列创建 html 文本条目列表(无循环)?
How to create a list of html text entries from data.frame columns in r (without loops)?
假设我有这个 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 行的解决方案。可能吗?
您可以使用 sprintf
和 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>"
有用的参考:Can you pass a vector to a vararg?: Vector to sprintf
假设我有这个 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 行的解决方案。可能吗?
您可以使用 sprintf
和 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>"
有用的参考:Can you pass a vector to a vararg?: Vector to sprintf