简体   繁体   中英

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. 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))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM