[R] Effeciently sum 3d table

David Winsemius dwinsemius at comcast.net
Mon Apr 16 21:42:00 CEST 2012


On Apr 16, 2012, at 3:26 PM, David Winsemius wrote:

>
> On Apr 16, 2012, at 2:43 PM, David A Vavra wrote:
>
>> Thanks Petr,
>>
>> I'm after T1 + T2 + T3 + ...
>
> Which would be one number ... i.e. the result you originally said  
> you did not want.
>
>> and your solution is giving a list of n items
>> each containing sum(T[i]). I guess I should have been clearer in  
>> stating
>> what I need.
>
> Or even now you _could_ be clearer. Do you want successive partial  
> sums? That would yield to:
>
> Reduce("+", listoftables, accumaulate=TRUE)

If Dunlap's interpretation is corect then consder this

  L <- lapply(1:50000, function(i) array(i:(i+7), c(2,2,2)))
  system.time({final <- L[[1]]
  for(i in seq_along(L)[-1]) final <- final + L[[i]]
  final}  )
#   user  system elapsed
#  0.179   0.002   0.187

  system.time(Reduce("+", L))
#   user  system elapsed
#  0.150   0.002   0.157

 > identical(Reduce("+", L), final)
[1] TRUE


>
>
>
>
>>
>> Cheers,
>> DAV	
>>
>>
>>
>> -----Original Message-----
>> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org 
>> ] On
>> Behalf Of Petr Savicky
>> Sent: Monday, April 16, 2012 11:07 AM
>> To: r-help at r-project.org
>> Subject: Re: [R] Effeciently sum 3d table
>>
>> On Mon, Apr 16, 2012 at 10:28:43AM -0400, David A Vavra wrote:
>>> I have a large number of 3d tables that I wish to sum
>>> Is there an efficient way to do this? Or perhaps a function I can  
>>> call?
>>>
>>> I tried using do.call("sum",listoftables) but that returns a  
>>> single value.
>>
>>>
>>> So far, it seems only a loop will do the job.
>>
>> Hi.
>>
>> Use lapply(), for example
>>
>> listoftables <- list(array(1:8, dim=c(2, 2, 2)), array(2:9,  
>> dim=c(2, 2,
>> 2)))
>> lapply(listoftables, sum)
>>
>> [[1]]
>> [1] 36
>>
>> [[2]]
>> [1] 44
>>
>> Hope this helps.
>>
>> Petr Savicky.
>>
>> ______________________________________________
>> 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.
>
> David Winsemius, MD
> West Hartford, CT
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list