你能将向量传递给可变参数吗?:向量到 sprintf [英] Can you pass a vector to a vararg?: Vector to sprintf
本文介绍了你能将向量传递给可变参数吗?:向量到 sprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个接受可变参数的函数,例如 sprintf().我想要类似的东西:
Let's say I have a function that takes variable arguments, such as sprintf(). I want something like:
sprintf("%s %s", "a", "b")
但我在向量 c("a", "b") 中有 "a" 和 "b".像
but I have "a" and "b" in a vector c("a", "b"). A call such as
sprintf("%s %s", c("a", "b"))
将因参数不足而产生错误.许多语言提供了一种将向量展平"为可变长度参数的方法.但我似乎无法在 R 中找到这样做的语法.有办法吗?
will produce an error for not enough arguments. Many languages provide a way to "flatten" a vector into a variable-length argument. But I cannot seem to find the syntax for doing so in R. Is there a way?
推荐答案
可以使用do.call
:
vec <- c("a","b")
do.call(sprintf, c(list("%s %s"), vec))
# [1] "a b"
这篇关于你能将向量传递给可变参数吗?:向量到 sprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文