Home > OS >  Averaging unique values in a matrix
Averaging unique values in a matrix

Time:11-28

I have list that contains two matrices. I would like to find the average for each of the matrices,using only the unique values and excluding the 0s in the matrices. Is there a good way to do this?

mat1.data <- c(0,6,3,8,0,6,8,10,0)
mat1 <- matrix(mat1.data,nrow=3,ncol=3,byrow=TRUE)
mat2.data <- c(0,5,5,1,0,1,7,23,0)
mat2 <- matrix(mat2.data,nrow=3,ncol=3,byrow=TRUE)

mat1 <- list(mat1, mat2)


CodePudding user response:

You can create a function, then apply the function to your matrix list with map.

library(tidyverse)
library(purrr)

# Function to get the mean.
get_mean <- function(x) {
  unlist(as.list(x)) %>%
    unique() %>%
    .[. != 0] %>%
    mean()
}

mean_unique <- purrr::map(mat1, get_mean)

Output

[[1]]
[1] 6.75

[[2]]
[1] 9

Data

mat1 <- list(structure(c(0, 8, 8, 6, 0, 10, 3, 6, 0),
               .Dim = c(3L, 3L)),
     structure(c(0, 1, 7, 5, 0, 23, 5, 1, 0),
               .Dim = c(3L, 3L)))

CodePudding user response:

Base R option, basically this is what @IRTFM suggested.

lapply(mat1, function(x) mean(unique(x[x!= 0])))

#[[1]]
#[1] 6.75

#[[2]]
#[1] 9

If you want a vector back use sapply instead of lapply.

  • Related