【问题标题】:How to use a list to supply argruments to sprintf in r如何在 r 中使用列表为 sprintf 提供参数
【发布时间】:2020-04-04 19:23:23
【问题描述】:

我正在尝试自动化一些填充我拥有的一些通用文本的代码。例如,我可能有两个字符串,其中包含不同数量的数字占位符。当前设置代码的方式需要传递字符串必须添加到其中的值的数量。如果我能以某种方式解压一个列表,以便它在 sprintf 中提供 ...,那么我可以跳过所有丑陋的 if 语句。

谢谢各位!

text_1 <- "This is a number %.1f"
text_2 <- "This is a number %.1f and this %.1f"

v1 <- 0.1
v2 <- 0.5
type = 1

if(type == 1)sprintf(text_1, v1)
if(type == 2)sprintf(text_2, v1, v2)

# ideally
l <- list(v1, v2)
sprint(text_2, unlist(l)) # something like unlist.

【问题讨论】:

  • 这个怎么样? do.call(sprintf, c(fmt = text_2, l))

标签: r string printf function-parameter


【解决方案1】:

我们可以使用reduce

library(purrr)
reduce(l, sprintf, fmt = text_2)
#[1] "This is a number 0.1 and this 0.5"

可以封装在函数中

f1 <- function(params, txt){
      reduce(params, sprintf, fmt = txt)
  }

f1(l, text_1)
#[1] "This is a number 0.1"

f1(l, text_2)
#[1] "This is a number 0.1 and this 0.5"

【讨论】:

  • 这正是我想要的!非常感谢(尤其是您的快速回复!)
猜你喜欢
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
相关资源
最近更新 更多