Mean of each element of a list of matrices

前端 未结 2 2053
南旧
南旧 2020-11-27 07:56

I have a list with three matrixes:

a<-matrix(runif(100))
b<-matrix(runif(100))
c<-matrix(runif(100))

mylist<-list(a,b,c)

I wou

2条回答
  •  一个人的身影
    2020-11-27 08:20

    Your question is not clear.

    For the mean of all elements of each matrix:

    sapply(mylist, mean)
    

    For the mean of every row of each matrix:

    sapply(mylist, rowMeans)
    

    For the mean of every column of each matrix:

    sapply(mylist, colMeans)
    

    Note that sapply will automatically simplify the results to a vector or matrix, if possible. In the first case, the result will be a vector, but in the second and third, it may be a list or matrix.

    Example:

    a <- matrix(1:6,2,3)
    b <- matrix(7:10,2,2)
    c <- matrix(11:16,3,2)
    mylist <- list(a,b,c)
    
    > mylist
    [[1]]
         [,1] [,2] [,3]
    [1,]    1    3    5
    [2,]    2    4    6
    
    [[2]]
         [,1] [,2]
    [1,]    7    9
    [2,]    8   10
    
    [[3]]
         [,1] [,2]
    [1,]   11   14
    [2,]   12   15
    [3,]   13   16
    

    Results:

    > sapply(mylist, mean)
    [1]  3.5  8.5 13.5
    
    > sapply(mylist, rowMeans)
    [[1]]
    [1] 3 4
    
    [[2]]
    [1] 8 9
    
    [[3]]
    [1] 12.5 13.5 14.5
    
    > sapply(mylist, colMeans)
    [[1]]
    [1] 1.5 3.5 5.5
    
    [[2]]
    [1] 7.5 9.5
    
    [[3]]
    [1] 12 15
    

提交回复
热议问题