Search code examples
c#rcode-translation

translate C# code to R for converting table to vector


I have a table like:

12 34  45  45 56
23 45  56  77 77
14 94  15  45 56
15 38  25  84 65
72 35  35  4  57
18 14  45  47 56
42 34  55  55 59

I would like to get in a vector the sum of the columns like

vector[0]= 12+23+14+15+72+18+42
vector[1]= 34+45+94+38+35+14+34
vector[2]= 45+56+15+25+35+45+55
vector[3]= 45+77+45+84+4 +47+55
vector[4]= 56+77+56+65+57+56+59

I did it in C# like

for ( i = 0; i < columns; i++)
{
  vector[i] += reader.GetDouble(i);
}

in which reader gets the corresponding element

But how to do this kind of thing in R?

so I would begin with..

for(i in (1:columns))
{

}

Solution

  • colSums(x)
    

    or

    apply(x,2,sum)
    

    if you want to be more general and less efficient.

    edit: if you want to be even less efficient and use a for loop,

    v <- numeric(ncol(x))
    for (i in seq(ncol(x))) {
       v[i] <- sum(x[,i])
    }
    

    We could continue making this less efficient by (1) using a nested for loop and (2) failing to preallocate space for the vectors ...

    See also: