的R - 矢量/阵列加法 [英] R - Vector/ Array Addition

查看:169
本文介绍了的R - 矢量/阵列加法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矢量或数组操作有点麻烦了。

我有三个三维阵列和我想找到他们的平均值。我怎样才能做到这一点?我们不能用平均值(),因为它只返回一个值。

更重要的是一些在阵列中的细胞都NA whic意思是,如果我只是将它们添加像

  A =(B + C + D)/ 3

的结果将显示NA为好。

如何才能让它识别,如果电池是那么NA只是跳过它。

如同

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

我要的平均输出这些向量

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

我们也不能使用 na.omit ,因为它会移动索引的顺序。

这是相应的code。我希望这将是有益的。

 为(1950年:2011){
    temp_JFM< - sst5_sst2 [,, year5_sst2 ==年和放大器; (month5_sst2> = 1和; month5_sst2&下; = 3)]
       K = 0
       JFM = 4 * K + 1
    为(ⅰ在1:72){
        为(以1:36 j)条{
            iposst5_sst2 [I,J,JFM]所述 - (temp_JFM [I,J,1] + temp_JFM [I,J,2] + temp_JFM [I,J,3])/ 3
        }
    }
}

Thnk你。<​​/ P>

它已经解决了。

可以在下面显示更正它最简单的方法。

  iposst5_sst2 [I,J,JFM&LT;  - 平均(temp_JFM [I,J,],na.rm = TRUE)


解决方案

下面是使这三个值的向量,这使得na.omit可用一个例子:

  vectorAverage&LT;  - 功能(A,B,C){
    z,其中; - 代表(NA,长度(A))    对(我在1:长度(A)){
        X'LT; - na.omit(C(A [I],B [I],C [I]))
        如果(长度(X)大于0)z [I] =平均(x)的
    }
    ž
}

致使

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

编辑:在第一个版本的输出错过楠

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)

解决方案

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.

这篇关于的R - 矢量/阵列加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆