在 R 中使用带有向量而不是可变数量的参数的 sprintf [英] use sprintf with a vector rather than a variable number of arguments in R
本文介绍了在 R 中使用带有向量而不是可变数量的参数的 sprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 R 中使用带有可变数量参数的 sprintf
函数.我可以将这些参数捆绑在一个字符向量或列表中,以避免将这些参数单独提供给 sprintf
吗?
I would like to use the sprintf
function in R with a variable number of arguments. Can I bundle these arguments together in a character vector or list in order to avoid supplying these arguments to sprintf
individually?
一个例子将阐明:
base_string = "(1) %s, (2) %s, (3) %s"
sprintf(base_string, "foo", "bar", "baz") # this works
sprintf(base_string, c("foo", "bar", "baz")) # this doesn't work
在 Python 中,我可以用
In Python I can accomplish this with
base_string = "(1) %s, (2) %s, (3) %s"
base_string % ("foo", "bar", "baz")
推荐答案
我们可以使用do.call
do.call(sprintf, c(fmt = base_string, as.list(v1)))
数据
v1 <- c("foo", "bar", "baz")
这篇关于在 R 中使用带有向量而不是可变数量的参数的 sprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文