R:如何对列表中的矩阵的多列求和? [英] R: How to sum multiple columns of matrices in a list?
本文介绍了R:如何对列表中的矩阵的多列求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对列表中的矩阵的多列求和,并且仅显示总和而不显示(计算)输入列(类似于我的
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)
我的预期结果是:
[[1]]
c new
[1,] 3 8
[[2]]
c new
[1,] 7 11
任何想法如何进行此列求和?谢谢
Any ideas how to do this column summation? Thanks
推荐答案
尝试以下方法:
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))
})
这篇关于R:如何对列表中的矩阵的多列求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文