Skip to content
Prev 316180 / 398506 Next

Pass vector as multiple parameters (as in python f(*x))

HI,

You could use ?Reduce() also in the second case:
lapply(vs,function(v){Reduce(f,as.list(v))})
#[[1]]
#[1] 10

#[[2]]
#[1] 6

#[[3]]
#[1] 1
A.K.





----- Original Message -----
From: Carlos Pita <carlosjosepita at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Friday, January 25, 2013 7:46 PM
Subject: Re: [R] Pass vector as multiple parameters (as in python f(*x))

Thanks Bert, do.call is exactly what I was looking for. What in lisp
is apply and in python f(*v).
Jeff I didn't pretend to imply that the mapping should by always
possible. lists for positional arguments and named lists for named
arguments would do the trick most of the times. It's pretty common in
dynamic languages.

That said, the specific task I have in mind is to index an array of an
arbitrary dimension n by a list of length n vectors, each one
representing <x1,...,xn> coordinates.

For example, if n=2, the array is the matrix m, and the list of vectors is vs:

m=matrix(1:16,4)
vs = list(c(2,3),c(2,2),c(1,1))

Then do.call would allow me to index m as follows:

lapply(vs, function(v) { do.call(`[`, append(list(m), v)) })

Alternatively:

f = function (...) { m[...] }
lapply(vs, function(v) { do.call(f, as.list(v)) })

Of course, I could just do m[v[1],v[2]] in this case, but the point is
that the dimension n would be a parameter of my function, not a
constant.

But if you know of a better or more r-esque solution I would be very
glad to hear of it.

Best regards
--
Carlos


Best regards
--
Carlos

Consider changing the called function's handling of arguments instead
to accept the vector of data directly if a vector makes sense, or to a
list if the arguments have a variety of types.
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.