R: How to sum multiple columns of matrices in a li

2019-09-04 18:51发布

This question already has an answer here:

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:

[[1]]
     c new
[1,] 3   8

[[2]]
     c new
[1,] 7  11

Any ideas how to do this column summation? Thanks

标签: r sum lapply
1条回答
看我几分像从前
2楼-- · 2019-09-04 19:21

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))
  })
查看更多
登录 后发表回答