Frage

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))
War es hilfreich?

Lösung

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)})
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top