平均矩阵中的唯一值
Posted
技术标签:
【中文标题】平均矩阵中的唯一值【英文标题】:Averaging unique values in a matrix 【发布时间】:2022-01-05 11:03:31 【问题描述】:我有一个包含两个矩阵的列表。我想找到每个矩阵的平均值,仅使用唯一值并排除矩阵中的 0。有什么好办法吗?
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)
【问题讨论】:
mean( unique( mat[ mat!=0] ) ) 用于一个这样的矩阵,只需将 lapply 与执行此操作的匿名函数一起使用。 【参考方案1】:您可以创建一个函数,然后使用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)
输出
[[1]]
[1] 6.75
[[2]]
[1] 9
数据
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)))
【讨论】:
【参考方案2】:Base R 选项,基本上这是@IRTFM 建议的。
lapply(mat1, function(x) mean(unique(x[x!= 0])))
#[[1]]
#[1] 6.75
#[[2]]
#[1] 9
如果您想要一个向量返回,请使用sapply
而不是lapply
。
【讨论】:
以上是关于平均矩阵中的唯一值的主要内容,如果未能解决你的问题,请参考以下文章
矩阵乘法中每个单元格的平均值,而不仅仅是 python 中的总和