[R] Newbie: colSums() compared with Matlab's sum()

Francesco Napolitano franapoli at gmail.com
Thu Dec 24 03:46:29 CET 2009


Hi all,

I'm trying to learn R after years of Matlab's experience. Here is an
issue I couldn't solve today.

Consider the following piece of code (written by memory):

for(i in 1:n){
    submat <- data[1:i,]
    C <- colSums(submat)
    }

The problem is that at the first iteration, data[1:1,] reduces to a
vector and colSums returns an error. This sounds really strange to me
because a sum-over-columns operation should have no problem working with
columns of length 1. Matlab's "sum()" works just fine in such case.

The error says that I need an at least 2D array. So I try using
matrix(data[1:i,]). Unfortunately this returns a column instead of a
row. So I could do t(matrix(data[1:i,])), but this would transpose the
also the sub-matrices from the 2nd iteration on. I could fix everything
with some "if" but it would be really terrible code :-/.

I'm sure I'm missing something because my neurons stick with Matlab
behaviour. Can you help me to understand what's wrong with my reasoning?

Thank you very much,
Francesco.




More information about the R-help mailing list