1

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
1
  • 4
    I guess you need grepl. Please show a small reproducible example and expected ouptut. colSums(mat[starts_with(row.names(mat), "A"),]) Commented Jul 9, 2020 at 22:28

1 Answer 1

1

We can use colSums with startsWith

colSums(mat[startsWith(row.names(mat), "A"),])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.