[R] do.call("+", ...)
Robin Hankin
r.hankin at noc.soton.ac.uk
Fri Nov 17 12:57:36 CET 2006
Hello everyone
thanks for the replies. My application (predictably) involves
arbitrary dimensioned arrays, so I will need to generalize
the suggestions slightly (except Peter Dalgaard's, which
works out-of-the-box).
At least I wasn't missing anything obvious about do.call().
Why is Peter Dalgaard's suggestion necessary? Why can't "+"
take more than two arguments?
On 17 Nov 2006, at 10:38, Peter Dalgaard wrote:
> rfrancois at mango-solutions.com writes:
>
>> Hi,
>>
>> You could stack your list in an array and then use apply :
>>
>> myArray <- array( unlist(lapply(1:3, f) ) , dim =c(2, 3, 3))
>> apply(myArray, c(1,2), sum)
>
> Or fixup "+" to take more than two arguments, e.g.
>
> "++" <- function(x, ...) if (nargs() == 1) x else x + Recall(...)
>
> f <- function(i){matrix((1:6)^i, 2, 3)}
> do.call("++", sapply(1:4, f, simplify=FALSE))
>
> ##
>
>> "++" <- function(x, ...) if (nargs() == 1) x else x + Recall(...)
>> f <- function(i){matrix((1:6)^i, 2, 3)}
>> do.call("++", sapply(1:4, f, simplify=FALSE))
> [,1] [,2] [,3]
> [1,] 4 120 780
> [2,] 30 340 1554
>
>
>
>
>> Cheers,
>>
>> Romain
>>
>> Quoting Robin Hankin <r.hankin at noc.soton.ac.uk>:
>>
>>> Hi
>>>
>>> How do I make do.call() take "+" as a function for a list of more
>>> than two elements?
>>>
>>> Toy problem follows:
>>>
>>>
>>> f <- function(i){matrix((1:6)^i,2,3)}
>>>
>>> # Thus f() returns a matrix of size 2x3; I want to add a whole bunch
>>> of such matrices,
>>> # as in f(1) + f(2) + f(3) + f(4)
>>>
>>> # But:
>>>
>>>
>>>
>>>> do.call("+",sapply(1:4,f,simplify=FALSE))
>>> Error in do.call("+", sapply(1:4, f, simplify = FALSE)) :
>>> operator needs one or two arguments
>>>
>>>
>>>
>>>
>>> Also,
>>>
>>>
>>>> do.call(sum,sapply(1:4,f,simplify=FALSE))
>>> [1] 2828
>>>
>>>
>>> doesn't do what I want (I would like a 2x3 matrix whose elements
>>> are the
>>> sum of corresponding elements in my list)
>>>
>>> How to do this nicely?
>>>
>>>
> ucible code.
--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
tel 023-8059-7743
More information about the R-help
mailing list