简体   繁体   中英

How to add two columns from each matrix in a list of matrices in R?

I have a list of matrices and I want to combine two columns by calculating the mean and, finally, remove one of them. I know how I could do it with just one matrix but not with many matrices in a list.

Let's say we have a matrix with 3 columns. This is what I want to do:

matrix <- matrix(1:9,ncol=3)
matrix[,2] <- (matrix[,2] + matrix[,3]) / 2
matrix <- matrix[,-3]

The removal of the column can be done like this:

list <- lapply(list, function(x)x[,-3])

But how can I achieve the first part with a list of matrices?

list <- list(matrix(1:9, ncol=3), matrix(3:11, ncol=3))

Do you mean something like this:

matrix_list <- list(m1 = matrix(runif(9), nrow=3), m2 = matrix(runif(9), nrow=3))
matrix_list <- lapply(matrix_list, function(x){
        x[,2] <- (x[,2] + x[,3]) / 2; 
        x <- x[,-3]; 
        return(x)})

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