我有包含兩個矩陣的串列。我想找到每個矩陣的平均值,僅使用唯一值并排除矩陣中的 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)
uj5u.com熱心網友回復:
您可以創建一個函式,然后使用 將該函式應用到您的矩陣串列中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)))
uj5u.com熱心網友回復:
Base R 選項,基本上這是@IRTFM 建議的。
lapply(mat1, function(x) mean(unique(x[x!= 0])))
#[[1]]
#[1] 6.75
#[[2]]
#[1] 9
如果你想要一個向量回傳使用sapply而不是lapply.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368264.html
