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

≡放荡痞女 提交于 2019-12-12 02:40:44

问题


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


回答1:


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))
  })


来源:https://stackoverflow.com/questions/39690633/r-how-to-sum-multiple-columns-of-matrices-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!