如何计算矩阵列表中特定行的总和
How do you calculate the sum of a specific row in a list of matrices
我有矩阵中的数据,矩阵存储在列表中,我想要每个矩阵中特定行的总和。
一些示例数据
A1<-matrix(0:9, nrow=5, ncol=2)
A2<-matrix(10:19, nrow=5, ncol = 2)
A3<-matrix(20:29, nrow=5, ncol = 2)
Mylist<-list(A1, A2, A3)
我可以得到每个矩阵中所有行的总和
lapply(Mylist, function(x) apply(x, 1, sum) )
但我只想要特定行的总和,可以是第 1 行,也可以是第 4 行,具体取决于我想查看的内容。我知道我可以从我用上面的代码生成的结果中读取它,但我想要一个更干净的解决方案,只给我结果。谢谢
您可以使用 purrr:map()
。
如果你知道输出类型(在本例中,似乎都是整数),你可以更具体一些,比如map_int()
。使用 map()
你会得到一个列表,有一个特定的 map
版本,比如 map_int()
,你会得到一个向量。
library(tidyverse)
ix <- 3 # let's say we want the sum of the third row
map_int(Mylist, ~sum(.x[ix, ]))
[1] 9 29 49
如果您关心的行索引随矩阵变化,您可以改用 map2()
,它需要两个相同长度的输入:
ixs <- c(1, 2, 3)
map2_int(Mylist, ixs, ~sum(.x[.y, ]))
[1] 5 27 49
或者,如果你需要在 base R 中工作,你可以只取 sum()
的所需索引(这里,ix
),你不需要 apply()
lapply()
:
lapply(Mylist, function(x) sum(x[ix, ]))
[[1]]
[1] 9
[[2]]
[1] 29
[[3]]
[1] 49
one.row.sum <- function(df, row.num) lapply(Mylist, function(df) sum(df[row.num, ]))
one.row.sum(Mylist, 1)
[[1]]
[1] 5
[[2]]
[1] 25
[[3]]
[1] 45
我有矩阵中的数据,矩阵存储在列表中,我想要每个矩阵中特定行的总和。
一些示例数据
A1<-matrix(0:9, nrow=5, ncol=2)
A2<-matrix(10:19, nrow=5, ncol = 2)
A3<-matrix(20:29, nrow=5, ncol = 2)
Mylist<-list(A1, A2, A3)
我可以得到每个矩阵中所有行的总和
lapply(Mylist, function(x) apply(x, 1, sum) )
但我只想要特定行的总和,可以是第 1 行,也可以是第 4 行,具体取决于我想查看的内容。我知道我可以从我用上面的代码生成的结果中读取它,但我想要一个更干净的解决方案,只给我结果。谢谢
您可以使用 purrr:map()
。
如果你知道输出类型(在本例中,似乎都是整数),你可以更具体一些,比如map_int()
。使用 map()
你会得到一个列表,有一个特定的 map
版本,比如 map_int()
,你会得到一个向量。
library(tidyverse)
ix <- 3 # let's say we want the sum of the third row
map_int(Mylist, ~sum(.x[ix, ]))
[1] 9 29 49
如果您关心的行索引随矩阵变化,您可以改用 map2()
,它需要两个相同长度的输入:
ixs <- c(1, 2, 3)
map2_int(Mylist, ixs, ~sum(.x[.y, ]))
[1] 5 27 49
或者,如果你需要在 base R 中工作,你可以只取 sum()
的所需索引(这里,ix
),你不需要 apply()
lapply()
:
lapply(Mylist, function(x) sum(x[ix, ]))
[[1]]
[1] 9
[[2]]
[1] 29
[[3]]
[1] 49
one.row.sum <- function(df, row.num) lapply(Mylist, function(df) sum(df[row.num, ]))
one.row.sum(Mylist, 1)
[[1]]
[1] 5
[[2]]
[1] 25
[[3]]
[1] 45