【问题标题】:How to create a list of html text entries from data.frame columns in r (without loops)?如何从 r 中的 data.frame 列创建 html 文本条目列表(没有循环)?
【发布时间】:2020-11-08 23:31:14
【问题描述】:

想象一下我有这个 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 行的解决方案。有可能吗?

【问题讨论】:

    标签: html r text r-glue


    【解决方案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>"
    

    有用的参考:Can you pass a vector to a vararg?: Vector to sprintf

    【讨论】:

    • 有没有办法在其中指定列名?否则它是完美的。我可以制作一个新的 df,但如果我能帮上忙,我宁愿不要。
    • @bartcubrich 一种方法可能是重新排序您的df,例如,尝试do.call(sprintf, c(list("Hello World&lt;br&gt; &lt;b&gt;%s %s the %s.&lt;/b&gt;"), df[, c("C", "B", "A")]))
    猜你喜欢
    • 1970-01-01
    • 2018-08-28
    • 2016-01-02
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多