1

I am troubleshooting the R's row sum function. I have the following vector called total:

 1   3
 1   45
 ..  ..
 20  45
 20  46

The vector has 20 different categories, and I would like to sum all the values for each category. My code is:

 rowsum(total[,c(1:20)], group = c(1:20))

But I get the following error:

 Error in rowsum.default(total[, c(1:2)], group = c(1:20))   incorrect length for 'group'

I am a bit confused because in the documentation, "group" is a vector/factor giving the grouping with one element per row of x.

Any help would be appreciated.

Thank you!

Johnathan
  • 1,877
  • 4
  • 23
  • 29
  • Both arguments should be of the same length. So you need to pass the entire first column with the group ids as the second argument. – Ramnath Mar 18 '14 at 18:58

2 Answers2

2

The second argument needs to be group memberships of the first one.

dat <- data.frame(
  value = runif(100),
  group = sample(1:20, 100, replace = T)
)

rowsum(dat$value, dat$group)
Ramnath
  • 54,439
  • 16
  • 125
  • 152
  • 1
    Thank you for taking the time of answering. I am sorry, but I don't understand. Could you please explain each step? I know that you are invoking a normal distribution. – Johnathan Mar 18 '14 at 20:33
0

You can also use tapply when you would like to break up a data into groups and do the same computation in the individual groups. You can see http://www.r-bloggers.com/r-function-of-the-day-tapply/ for more information.

Dinesh
  • 2,194
  • 3
  • 30
  • 52