Reputation: 99418
Suppose f
is a function which can accept a varying number of arguments. I have a vector x
whose entries are used as the arguments of f
.
x=c(1,2,3)
f(x[], otherarguments=100)
What is the correct and simple way to pass the entries of x
as arguments to f
? Thanks!
E.g.
I want to convert
t1 = traceplot(output.combined[1])
t2 = traceplot(output.combined[2])
t3 = traceplot(output.combined[3])
t4 = traceplot(output.combined[4])
grid.arrange(t1,t2,t3,t4,nrow = 2,ncol=2)
to something like
tt=c()
for (i in 1:4){
tt[i] = traceplot(output.combined[i])
}
grid.arrange(tt[],nrow = 2,ncol=2)
Upvotes: 3
Views: 79
Reputation: 547
As @agstudy above stated, what you are actually looking for is vectorizing the function f()
rather than trying to pass a vector to a non-vectorized function. All vectorized functions in R are of the form
vectorized_f <- function(X) {
x1 <- X[1]
x2 <- X[2]
x3 <- X[3]
# ...
xn <- X[length(X)]
# Do stuff
}
As an example let's do f <- function(x1, x2, x3) x1 + x2 + x3
. This function is not vectorized, thus trying to pass a vector requires a work-around. Rather than supplying three arguments you would write f()
as follows:
vectorized_f <- function(X) {
x1 <- X[1]
x2 <- X[2]
x3 <- X[3]
x1 + x2 + x3
}
Of course you can also try to keep it non-vectorized, but as I said, that would require a work-around. This could be done for example like this:
f <- function(x1, x2, x3) x1 + x2 + x3
X <- c(1, 2, 3)
funcall_string <- paste("f(", paste(X, collapse = ","), ")", collapse = "")
# this looks like this: "f( 1,2,3 )"
eval(parse(text = funcall_string))
# [1] 6
But this is actually way slower than the vectorized version.
system.time(for(i in 1:10000) {
funcall_string <- paste("f(", paste(X, collapse = ","), ")", collapse = "")
eval(parse(text = funcall_string))
})
User System verstrichen
2.80 0.01 2.85
Vs
system.time(for(i in 1:10000) vectorized_f(X))
User System verstrichen
0.05 0.00 0.05
Hth, D
Upvotes: 1
Reputation: 121568
Here one option:
I assume you have this function , and you want to "vectorize", x,y,z argument:
ss <-
function(x,y,z,t=1)
{
x+y+z*t
}
You can wrap it in a function, with a vector as argument for (x,y,z) and '...' for other ss arguments:
ss_vector <-
function(vec,...){
ss(vec[1],vec[2],vec[3],...)
}
Now you can call it like this :
ss_vector(1:3,t=2)
[1] 9
which is equivalent to :
ss(1,2,3,t=2)
[1] 9
Upvotes: 2