简体   繁体   English

R-向量/数组加法

[英]R - Vector/ Array Addition

I a having a little trouble with vector or array operations. 向量或数组运算有点麻烦。

I have three 3D arrays and i wanna find the average of them. 我有三个3D阵列,我想找到它们的平均值。 How can i do that? 我怎样才能做到这一点? we can't use mean() as it only returns a single value. 我们不能使用mean()因为它仅返回一个值。

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. 的结果也将显示NA。

How can i let it recognise if the cell is NA then just skip it. 我如何让它识别该单元格是否为NA,然后跳过它。

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. 我们也不能使用na.omit ,因为它将移动索引的顺序。

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)

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. 我不确定您想要的输出是什么,但是我猜测您真正想要构建的不是三个3D阵列,而是一个可以apply 4D阵列。

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)

Here's an example which makes a vector of the three values, which makes na.omit usable: 这是一个使三个值成为向量的示例,使na.omit可用:

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. 编辑:在第一个版本的输出中缺少NaN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM