-2

I have a matrix e.g.

     [,1]     [,2]
[1,]  11212    10
[2,]  133      10
[3,]   15      9
[4,]   10      9

I want to add up the times that column 2 is repeated and display this in column 1.

For this example the output would be


     [,1]     [,2]
[1,]   11345    1
[2,]   25    0

Cheers

  • This is almost a duplicated of the [FAQ on How to sum by group](https://stackoverflow.com/q/1660124/903061). Some of the answers there assume a data frame, not a matrix (though you could convert), but I'd recommend reading through those if you want a nice overview of ways to do this. – Gregor Thomas Apr 22 '20 at 15:11

2 Answers2

1

Maybe you can try the code below

mout <- cbind(unname(tapply(m[,1], factor(m[,2],levels = unique(m[,2])), sum)),unique(m[,2]))


> mout
     [,1] [,2]
[1,]   13    1
[2,]   15    0

Data

m <- matrix(c(12,1,5,10,1,1,0,0),ncol = 2)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

Depending on your further steps, you should think about using a data.table (package data.table).

dt <- data.table::data.table(x=c(12, 1, 5, 10), y=c(1, 1, 0, 0))

dt[,.(x=sum(x)), by=y]
Martin Gal
  • 16,640
  • 5
  • 21
  • 39