【问题标题】:How to calculate element-wise mean of a list of matrices while excluding NaNs如何在排除 NaN 的同时计算矩阵列表的元素平均值
【发布时间】:2021-07-13 00:39:27
【问题描述】:

假设我有矩阵列表。您将如何计算另一个矩阵,其元素是矩阵列表的元素均值,考虑和排除 NaN?假设我们有一个矩阵列表: )

> A
     [,1] [,2] [,3]
[1,]   1    4    7
[2,]   2    5    8
[3,]   3    6    9

> B
     [,1] [,2] [,3]
[1,]   2    5    8
[2,]  NaN  NaN  NaN
[3,]   4    7   10

> C
     [,1] [,2] [,3]
[1,]   3    3    6
[2,]   2    3    7
[3,]  NaN  NaN  NaN

> my.list <- list(A, B, C)

我想要的输出是:

     [,1] [,2] [,3]
[1,]   2    4    7
[2,]   2    4   7.5
[3,]  3.5  6.5  9.5

如您所见,我希望计算列表的元素平均值,但不包括列表中矩阵的 NaN 值。因此,例如输出的元素 [1,1] 是 (1 + 2 + 3) / 3 = 2,但输出的元素 [3,1] 是 (3 + 4) / 2 = 3.5,因为我们排除了NaN 在矩阵 B 中的那个位置。知道如何计算吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    转换为array,然后使用apply循环,得到mean

     apply(simplify2array(my.list), c(1, 2), FUN = mean, na.rm = TRUE)
    

    -输出

          [,1] [,2] [,3]
    [1,]  2.0  4.0  7.0
    [2,]  2.0  4.0  7.5
    [3,]  3.5  6.5  9.5
    

    或者可以循环一维并使用rowMeans

    apply(simplify2array(my.list), 2, rowMeans, na.rm = TRUE)
         [,1] [,2] [,3]
    [1,]  2.0  4.0  7.0
    [2,]  2.0  4.0  7.5
    [3,]  3.5  6.5  9.5
    

    或者另一种选择是

    library(dplyr)
    library(purrr)
    library(data.table)
     map_dfr(my.list, as.data.frame, .id = 'grp') %>% 
       group_by(grp = rowid(grp)) %>% 
       summarise(across(everything(), mean, na.rm = TRUE), 
           .groups = 'drop') %>%
       select(-grp)
    # A tibble: 3 x 3
         V1    V2    V3
      <dbl> <dbl> <dbl>
    1   2     4     7  
    2   2     4     7.5
    3   3.5   6.5   9.5
    

    数据

    my.list <- list(structure(1:9, .Dim = c(3L, 3L)), structure(c(2, NaN, 4, 
    5, NaN, 7, 8, NaN, 10), .Dim = c(3L, 3L)), structure(c(3, 2, 
    NaN, 3, 3, NaN, 6, 7, NaN), .Dim = c(3L, 3L)))
    

    【讨论】:

      【解决方案2】:
        # input prepare
        A= matrix(1:9,nrow=3,ncol=3)
        B = matrix(2:10,nrow=3,ncol=3)
        B[2,] = NaN
        C =matrix(c(3,2,NaN,3,3,NaN,6,7,NaN),nrow=3,ncol=3)
      
        # flatten every matrix as a column of rowMeans big matrix
        # so rowMeans do element-wise process
        mat.as.vec.list = lapply(list(A,B,C), as.vector)
        bind.by.col= do.call(cbind, mat.as.vec.list)
      
        
        mean.by.row = rowMeans(bind.by.col, na.rm = T)
      
        #convert back to matrix
        dim(mean.by.row) = dim(A)
        mean.by.row
      
           [,1] [,2] [,3]
      [1,]  2.0  4.0  7.0
      [2,]  2.0  4.0  7.5
      [3,]  3.5  6.5  9.5
      
      
        
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        • 2014-01-21
        • 2021-10-29
        • 1970-01-01
        相关资源
        最近更新 更多