[R] updating elements of a list of matrixes without 'for' cycles

Bert Gunter bgunter.4567 at gmail.com
Mon Feb 1 17:38:14 CET 2016


A perhaps faster approach takes advantage of the column major ordering
of arrays and the expand.grid() function. I say "perhaps" faster,
because "apply" family functions are still actually loops at the R
level.

Anyway, try this (using your little example):

## create a data frame (which is also a list) of i,j,k,index combinations:
z <- expand.grid(i=1:2, j= 1:2, k = 1:2)

## Use do.call() to feed the columns of z to mapply
yourarray <- array(do.call(mapply,c(prod,z)),dim=c(2,2,2))


Cheers,
Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Mon, Feb 1, 2016 at 6:29 AM, Jue Lin-Ye <jl.iccp at gmail.com> wrote:
>>
>> Date: Sat, 30 Jan 2016 01:03:30 +0000
>> From: Matteo Richiardi <
>>
>> Matteo.Richiardi at maths.ox.ac.uk>
>> To: r-help at r-project.org
>> Subject: [R] updating elements of a list of matrixes without 'for'
>>         cycles
>> Message-ID:
>>         <
>> CABSrU1LkOHUZ8M9JW1ju+neMksPriRRTD_0WzOtRLWi3z6dA9w at mail.gmail.com>
>> Content-Type: text/plain; charset=UTF-8
>>
>> Hi, following an earlier suggestion from the list, I am storing my
>> data in a "cube", i.e. an array of matrixes.
>> Is there any smarter way of updating the elements of the cube through
>> a function, other than the three 'for' cycles in the example below?
>> (please note that the example is simplistic; in particular, my
>> function is more complicated).
>>
>> # parameters
>> I <- 2L
>> J <- 2L
>> H <- 2L
>>
>> # data container: an array of matrixes
>> mycube <- array(dim=c(I,J,H))
>>
>> # initialisation
>> for (h in 1:H) {
>>   init <- matrix(c(rep(0,J)),nrow=I,ncol=J)
>>   mycube[,,h] <- init
>> }
>>
>> # function
>> foo = function(i,j,h){
>>   mycube[i,j,h] <<- i*j*h
>> }
>>
>> # update
>>
>> for(h in 1:H){
>>   # males:
>>   for(i in 1:I)
>>     for(j in 1:J)
>>       foo(i,j,h)
>> }
>>
>> Thanks a lot for your help. Matteo
>>
>>
>>
> Greetings! Have you tried sapply() on this script?
>
> --
> Jue
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.



More information about the R-help mailing list