简体   繁体   English

如何在R矩阵列表中的每个矩阵中添加两列?

[英]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. 假设我们有一个3列的矩阵。 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)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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