简体   繁体   中英

How to combine subsequent list elements into a new list in R?

For example: I have a list of matrices, and I would like to evaluate their differences, sort of a 3-D diff. So if I have:

m1 <- matrix(1:4, ncol=2)
m2 <- matrix(5:8, ncol=2)
m3 <- matrix(9:12, ncol=2)
mat.list <- list(m1,m2,m3)

I want to obtain

mat.diff <- list(m2-m1, m3-m2)

The solution I found is the following:

mat.diff <- mapply(function (A,B) B-A, mat.list[-length(mat.list)], mat.list[-1])

Is there a nicer/built-in way to do this?

You can do this with just lapply or other ways of looping:

mat.diff <- lapply( tail( seq_along(mat.list), -1 ), 
                    function(i) mat.list[[i]] - mat.list[[ i-1 ]] )

You can use combn to generate the indexes of matrix and apply a function on each combination.

       combn(1:length(l),2,FUN=function(x) 
            if(diff(x) == 1)         ## apply just for consecutive index 
                  l[[x[2]]]-l[[x[1]]], 
                  simplify = FALSE)  ## to get a list 

Using @Arun data, I get :

[[1]]
     [,1] [,2]
[1,]    4    4
[2,]    4    4

[[2]]
NULL

[[3]]
     [,1] [,2]
[1,]    4    4
[2,]    4    4

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