[英]In R, with a list of matrices, how can I quickly find the difference between the first and second row in each matrix in the list?
Suppose I have a list like the following: 假设我有一个类似以下的列表:
my.list <- replicate(100, matrix(rnorm(50), nrow = 2), simplify = FALSE)
Which contains 100 elements, each of which is a 2 by 25 matrix. 其中包含100个元素,每个元素都是2 x 25矩阵。 I would like to find the difference between the second and first row for each matrix in the array. 我想找到数组中每个矩阵的第二行和第一行之间的差异。 So looking at the first matrix, which is: 因此,看一下第一个矩阵,即:
> my.list[[1]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] -0.6439385 -1.0432182 -0.8209565 -0.39554834 0.11923593 -0.7924756 0.9486538 -0.5773245
[2,] -0.2485357 0.3248831 0.0510696 -0.01372084 -0.03815523 -2.0050425 1.0868125 -2.5684173
[,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] -0.2007935 -0.4698965 -1.2655670 -0.09743834 -0.1665144 0.2858232 -1.5013000 1.3658686
[2,] 0.7978383 0.1259687 -0.0956009 1.63116327 -2.6593684 1.5665240 0.8206011 0.1437499
[,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24]
[1,] 1.0984398 1.423985 -1.4280701 -0.3175241 0.3076809 -1.9266312 -0.2429406 -0.9616004
[2,] -0.6761191 1.201523 -0.4578632 1.8785372 -0.2124522 -0.9074403 -0.9615636 1.4551716
[,25]
[1,] -0.2794859
[2,] -0.9004094
I would like to get: 我想得到:
my.list[[1]][2,]-my.list[[1]][1,]
[1] 0.3954028 1.3681013 0.8720261 0.3818275 -0.1573912 -1.2125669 0.1381587 -1.9910928
[9] 0.9986318 0.5958652 1.1699661 1.7286016 -2.4928540 1.2807008 2.3219011 -1.2221187
[17] -1.7745590 -0.2224617 0.9702069 2.1960613 -0.5201331 1.0191909 -0.7186231 2.4167720
[25] -0.6209235
but for ALL the matrices. 但对于所有矩阵。 Is there a simple way to do this? 有没有简单的方法可以做到这一点? Thanks. 谢谢。
您可以使用lapply
计算每个矩阵的减法
lapply(my.list, function(x) x[2,]-x[1,])
Or another option is 或另一个选择是
library(purrr)
map(my.list, ~ c(diff(head(.x, 2))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.