Reputation: 720
I can do this in python but in R I cannot find how to do conditions.
I have a matrix with colnames(mat), rownames(mat). For each column, I need to calculate sum of values if a row begins from a certain pattern. Let's say I need to sum up only the values where the row name starts from 'A'.
I tried this:
for(i in colnames(mat)) {
sum_A=0
for (j in rownames(mat)) {
sum_A<-sum(mat[ j == 'A^', i])
}
}
A
It gives me this output:
[1] 0
Upvotes: 1
Views: 616
Reputation: 887851
We can use colSums
with startsWith
colSums(mat[startsWith(row.names(mat), "A"),])
Upvotes: 1