[英]How do you calculate the sum of a specific row in a list of matrices
I have data in matrices and the matrices are stored in a list, and I want the sum of the a specific row in each matrix. 我有矩阵中的数据,并且矩阵存储在列表中,并且我希望每个矩阵中特定行的总和。
some example data 一些示例数据
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)
I can get the sum of all rows in each matrix with 我可以得到每个矩阵中所有行的总和
lapply(Mylist, function(x) apply(x, 1, sum) )
but I only want the sum of a specific row, could be row 1, could be row 4, depending on what I want to look at. 但我只希望特定行的总和,可能是第1行,可能是第4行,具体取决于我要查看的内容。 I know I can read it off of the results I generate with the code above but I want a cleaner solution that only gives me the results. 我知道我可以从上面的代码生成的结果中读取出来,但是我想要一个更干净的解决方案,它只能为我提供结果。 Thanks 谢谢
You can use purrr:map()
. 您可以使用purrr:map()
。
If you know the output type (in this case, seems to be all integers), you can be more specific, like map_int()
. 如果您知道输出类型(在这种情况下,似乎是所有整数),则可以更加具体,例如map_int()
。 With map()
you'll get a list back, with a specific map
version, like map_int()
, you get a vector back instead. 使用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
If the row index you care about changes per matrix, you can use map2()
instead, which takes two inputs of the same length: 如果您关心的行索引是每个矩阵的变化,则可以改用map2()
,它需要两个长度相同的输入:
ixs <- c(1, 2, 3)
map2_int(Mylist, ixs, ~sum(.x[.y, ]))
[1] 5 27 49
Alternately, if you need to work in base R, you can just take the desired index (here, ix
) of sum()
, you don't need apply()
inside lapply()
: 或者,如果您需要在基础R工作,你可以只取所需的索引(在这里, ix
)的sum()
你不需要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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.