我有一个像这样的列表
list <- structure(list(`1` = structure(c(274L, 173L), .Dim = 2L, .Dimnames = structure(list(
c("2004", "2005")), .Names = ""), class = "table"), `2` = structure(73L, .Dim = 1L, .Dimnames = structure(list(
"2005"), .Names = ""), class = "table"), `3` = structure(c(334L,
365L, 366L, 365L, 365L, 365L, 366L, 365L, 287L), .Dim = 9L, .Dimnames = structure(list(
c("1990", "1991", "1992", "1993", "1994", "1995", "1996",
"1997", "1998")), .Names = ""), class = "table"), `4` = structure(139L, .Dim = 1L, .Dimnames = structure(list(
"2001"), .Names = ""), class = "table"), `5` = structure(71L, .Dim = 1L, .Dimnames = structure(list(
"2009"), .Names = ""), class = "table"), `6` = structure(77L, .Dim = 1L, .Dimnames = structure(list(
"1997"), .Names = ""), class = "table")), .Names = c("1",
"2", "3", "4", "5", "6"))
此列表的第一级是上升数字。在第二级中,我们有多年作为列名的表。
我想构建列名为2005的第二级所有元素的总和。 我该怎么做?
答案 0 :(得分:3)
您可以使用sapply
和[
的组合。
> sum(sapply(list, `[`, "2005"), na.rm=TRUE)
[1] 246
答案 1 :(得分:1)
这样就可以了解
get2005 <- function(x){
x[names(x) %in% 2005]
}
sum(unlist(lapply(list, get2005)))