[R] Help with multidimensional array

Bert Gunter gunter.berton at gene.com
Tue Mar 29 05:00:24 CEST 2011


Arrays are vectors stored in column major order. Hence

H <- apply( H12*rep(hessian_lambda,e = n*k), 1:2, sum)
## but check that this gives what you want

I'm pretty sure this is faster than the alternatives that were
proposed, but whether it's much (or even noticeably)  faster, I don't
know.



-- Bert


On Mon, Mar 28, 2011 at 5:56 PM, Giuseppe <neox86 at gmail.com> wrote:
> Dennis,
>
> Yes, Reduce works, but unfortunately it does not speed up the
> evaluation time (actually, it makes it a little bit slower).
>
> Thank you anyway.
>
>
>
> On Tue, Mar 29, 2011 at 2:21 AM, Dennis Murphy <djmuser at gmail.com> wrote:
>> Hi:
>>
>> Is this what you're after?
>>
>> m <- array(1:27, c(3, 3, 3))
>> xx <- 1:3
>> Reduce('+', lapply(xx, function(k) xx[k] * m[, , k]))
>>
>>> m
>> , , 1
>>
>>      [,1] [,2] [,3]
>> [1,]    1    4    7
>> [2,]    2    5    8
>> [3,]    3    6    9
>>
>> , , 2
>>
>>      [,1] [,2] [,3]
>> [1,]   10   13   16
>> [2,]   11   14   17
>> [3,]   12   15   18
>>
>> , , 3
>>
>>      [,1] [,2] [,3]
>> [1,]   19   22   25
>> [2,]   20   23   26
>> [3,]   21   24   27
>>
>>> xx <- 1:3
>>> Reduce('+', lapply(xx, function(k) xx[k] * m[, , k]))
>>      [,1] [,2] [,3]
>> [1,]   78   96  114
>> [2,]   84  102  120
>> [3,]   90  108  126
>>
>> HTH,
>> Dennis
>>
>>
>> On Mon, Mar 28, 2011 at 4:10 PM, Giuseppe <neox86 at gmail.com> wrote:
>>>
>>> I have the following situation.
>>>
>>> H12 is an array of dimension (n,k,m) and hessian_lambda is a numeric
>>> of length m.
>>>
>>> I need to multiply each matrix H12[,,1], H12[,,2], ..., H12[,m] by
>>> hessian_lambda[1], hessian_lambda[2], ..., hessian_lambda[m],
>>> respectively, and then add the resulting (n,k) matrices. What I am
>>> using at the moment is the following code:
>>>
>>> H <- matrix(0, n, k)
>>>  for(j in 1:(m)) {
>>>        H <- H + H12[,,j]*hessian_lambda[j]
>>>  }
>>>
>>> Does anybody see a way to speed up this without using loop? (The
>>> output needs to be a matrix).
>>>
>>> Thank you for your time.
>>>
>>> ______________________________________________
>>> 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.
>>
>>
>
> ______________________________________________
> 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.
>



-- 
Bert Gunter
Genentech Nonclinical Biostatistics
467-7374
http://devo.gene.com/groups/devo/depts/ncb/home.shtml



More information about the R-help mailing list