R - Vector/ Array Addition

北慕城南 提交于 2020-01-30 08:46:06

问题


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() as it only returns a single value.

The more important is some of the cells in the arrays are NA whic mean if i just add them like

A = (B + C + D)/3 

The results of will show NA as well.

How can i let it recognise if the cell is NA then just skip it.

Like

 A = c(NA, 10, 15, 15, NA)
 B = c(10, 15, NA, 22, NA)
 C = c(NA, NA, 20, 26, NA)

I wanna the output of average these vectors be

(10, (10+15)/2, (15+20)/2, (15+22+26)/3, NA)

We also can't use na.omit, because it will move the order of indexes.

This is the corresponding code. i wish it would be helpful.

for (yr in 1950:2011) {
    temp_JFM <- sst5_sst2[,,year5_sst2==yr & (month5_sst2>=1 & month5_sst2<=3)]
       k = 0
       jfm=4*k+1
    for (i in 1:72) {
        for (j in 1:36) {
            iposst5_sst2[i,j,jfm] <- (temp_JFM[i,j,1]+temp_JFM[i,j,2]+temp_JFM[i,j,3])/3
        }
    }      
}

Thnk you.

It already been solved.

The easiest way to correct it can be shown below.

iposst5_sst2[i,j,jfm] <- mean(temp_JFM[i,j,],na.rm=TRUE)

回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/9900690/r-vector-array-addition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!