1

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))
{

}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
edgarmtze
  • 24,683
  • 80
  • 235
  • 386

1 Answers1

5
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:

Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Do I assign that to a vector? `vector<-colSums(x)` – edgarmtze Sep 17 '11 at 00:02
  • Is there any way to use a for loop, just to know? – edgarmtze Sep 17 '11 at 00:06
  • 5
    @cMinor It's best to break your for loop habit now, early on, if you're learning R. Many operations and functions are already vectorized for you. If you find yourself writing a for loop, odds are good that there's already a function that does that task more efficiently (and with less typing). Alarm bells should _really_ be ringing if you find yourself writing a nested for loop. (Obviously, they are unavoidable in some cases, but stil...) – joran Sep 17 '11 at 00:13
  • @yoran: I don agree that you should try to avoid all loops. Using loops can increase code readability and understanding of algorithms (and thus avoid errors). Often the performance impact is negligible (eg in a monte carlo analysis) and you becom e a victime of [http://scientopia.org/blogs/goodmath/2011/05/03/the-perils-of-premature-optimization/](premature optimization]. – johanvdw Sep 17 '11 at 19:45