[R] using apply function and storing output

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Fri Oct 15 09:46:29 CEST 2010


one efficient way to do this, avoiding loops, is using the rowsum() 
function, e.g.,

mat <- matrix(rnorm(1710*244), 1710, 244)

id <- rep(seq_len(570), each = 3)
means <- rowsum(mat, id, FALSE) / 3

Regarding the second part of your question, indeed a "gold" rule of 
efficient R programming when it comes to loops is to pre-allocate the 
output object. Check for instance,

system.time({
     x <- NULL
     for (i in 1:5e04) x <- c(x, rnorm(1))
})

versus

system.time({
     x <- numeric(5e04)
     for (i in 1:5e04) x[i] <- rnorm(1)
})


I hope it helps.

Best,
Dimitris


On 10/15/2010 9:34 AM, David A. wrote:
>
> Hi list,
>
> I have a 1710x244 matrix of numerical values and I would like to calculate the mean of every group of three consecutive values per column to obtain a new matrix of 570x244.  I could get it done using a for loop but how can I do that using apply functions?
> In addition to this, do I have to initizalize a 570x244 matrix with 0's to store the calculated values or can the output matrix be generated while calculating the mean values?
>
> Cheers,
>
> Dave
>   		 	   		
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list