Yulia Kentieva
Yulia Kentieva

Reputation: 720

How to calculate sum of values in each column based on row names in R?

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

Answers (1)

akrun
akrun

Reputation: 887851

We can use colSums with startsWith

colSums(mat[startsWith(row.names(mat), "A"),])

Upvotes: 1

Related Questions