R - Vector/ Array Addition

前端 未结 2 880
一向
一向 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: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.

提交回复
热议问题