Максим Усик
Максим Усик

Reputation: 119

How to add certain elements of column in Matrix in R?

N* [1]| [2] | [3]
1* | 3 | 20 | 3 |
2* | 2 | 10 | 3 |
3* | 3 | 25 | 3 |
4* | 1 | 15 | 3 |
5* | 3 | 30 | 3 |

Can you help me to get a sum of second column, but only sum of elements that has 3 in the first row. For example in that matrix it is 20+25+30=75. In a fastest way (it's actually big matrix).

P.S. I tried something like this with(Train, sum(Column2[,"Date"] == i)) As you can see I need sum Of Colomn2 where date has certain meaning (from 1 to 12)

Upvotes: 0

Views: 132

Answers (1)

akrun
akrun

Reputation: 887501

We can create a logical index with the first column and use that to subset the second column and get the sum

 sum(m1[m1[,1]==3,2])

EDIT: Based on @Richard Scriven's comment.

Upvotes: 2

Related Questions