[R] Newbie: colSums() compared with Matlab's sum()
Brian G. Peterson
brian at braverock.com
Thu Dec 24 04:38:48 CET 2009
Francesco Napolitano wrote:
> Il giorno mer, 23/12/2009 alle 22.14 -0500, David Winsemius ha scritto:
>>> for(i in 1:n){
>>> submat <- data[1:i,]
>>> C <- colSums(submat)
>>> }
>>>
>> In R the loop is not necessary, even confusing as you are demonstrating:
>>
>> > mat <- matrix(rnorm(100), nrow=10) # 10 x 10
>> > colSums(mat[1:5, ]) # sums of 1st 5 rows
>> [1] 3.33331735 0.86672248 -3.10971483 1.23620455 -0.31887421
>> -0.50544837
>> [7] 3.13636155 0.02175862 -2.18816961 -1.31760196
>
> It would be unnecessary also in Matlab. In the real code I need to store
> the partial sums (the example overwrites them, so it looks like wasted
> loops).
try:
data <- matrix(rnorm(100), nrow=10) # 10 x 10
apply(data,2,cumsum)
if you want to store the partial sums
(that was an important bit of information you left out)
More information about the R-help
mailing list