R - Vector/ Array Addition

前端 未结 2 875
一向
一向 2021-01-24 11:14

I a having a little trouble with vector or array operations.

I have three 3D arrays and i wanna find the average of them. How can i do that? we can\'t use mean()

相关标签:
2条回答
  • 2021-01-24 11:25

    I'm not entirely sure what your desired output is, but I'm guessing that what you really want to build is not three 3D arrays, but one 4D array that you can then use apply on.

    Something like this:

    #Three 3D arrays...
    A <- array(runif(1:27),dim = c(3,3,3))
    B <- array(runif(1:27),dim = c(3,3,3))
    C <- array(runif(1:27),dim = c(3,3,3))
    
    #Become one 4D array
    D <- array(c(A,B,C),dim = c(3,3,3,3))
    
    #Now we can simply apply the function mean
    # and use it's na.rm = TRUE argument.
    apply(D,1:3,mean,na.rm = TRUE)
    
    0 讨论(0)
  • 2021-01-24 11:45

    Here's an example which makes a vector of the three values, which makes na.omit usable:

    vectorAverage <- function(A,B,C) {
        Z <- rep(NA, length(A))
    
        for (i in 1:length(A)) {
            x <- na.omit(c(A[i],B[i],C[i]))
            if (length(x) > 0) Z[i] = mean(x)
        }
        Z
    }
    

    Resulting in:

    vectorAverage(A,B,C)
    [1] 10.0 12.5 17.5 21.0   NA
    

    Edited: Missed the NaN in the output of the first version.

    0 讨论(0)
提交回复
热议问题