N.Varela N.Varela - 10 months ago 68
R Question

R: How to sum multiple columns of matrices in a list?

I want to sum multiple columns of matrices in a list and only show the sum without showing the (calculation) input columns (similar to my former question on data frames). Thanks for the former answers, however I struggled to implement the ideas on matrices. Here an example:

ls <- list(matrix(c(1, 5, 3, 2), ncol=4), matrix(c(NA, 2, 7, 9), ncol=4))
countries <- c("a", "b", "c", "d")
ls <- lapply(ls, "colnames<-", countries)

my expected result is:

c new
[1,] 3 8

c new
[1,] 7 11

Any ideas how to do this column summation? Thanks

Answer Source

Try below:

calc <- c("a", "b", "d")
keep <- "c"

lapply(ls, function(i){
  cbind(i[, keep, drop = FALSE],
        new = rowSums(i[, calc, drop = FALSE], na.rm = TRUE))