【问题标题】:Excluding specific row elements from row-wise function evaluation for 3D array [r]从 3D 数组 [r] 的逐行函数评估中排除特定的行元素
【发布时间】:2013-09-14 04:40:58
【问题描述】:

我想将自定义函数应用于 3d 数组的每一行,不包括存储在向量 nul 中的特定值。对于数组的第 i 行(任一层),我想从评估中排除该行中与向量 nul 中第 i 个值匹配的所有值。

  mat <- rep(cbind(c(1,3,0,1,4),c(0,4,1,2,1), c(2,3,0,4,0), c(1,0,4,2,0), c(0,2,3,0,1)),2)
  arr <- array(mat, dim=c(5,5,2))
  nul <- c(1,3,5,8,4)

我尝试了很多不同的方法,但最接近的是:

 x1 <- apply(arr,c(1,3), function(x)myfun(x[x!=(nul)]))

但是,这会导致 arr 中的行元素被排除在外,这些行元素与 nul 中的每一行的对应行元素匹配。

“myfun”是为了简单起见的总结,但实际上这会更复杂:

> nul
[1] 1 3 5 8 4
> arr
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    2    1    0
[2,]    3    4    3    0    2
[3,]    0    1    0    4    3
[4,]    1    2    4    2    0
[5,]    4    1    0    0    1

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    2    1    0
[2,]    3    4    3    0    2
[3,]    0    1    0    4    3
[4,]    1    2    4    2    0
[5,]    4    1    0    0    1

> x1
     [,1] [,2]
[1,]    3    3
[2,]   12   12
[3,]    8    8
[4,]    8    8
[5,]    6    6

如您所见,仅排除了位置 [1,1,1] 处的“1”,而不是该行中的每个匹配值。此外,该函数在每一行中都排除了“1”,而不仅仅是第一个。

想要的输出是:

[1,]    2    2
[2,]    6    6
[3,]    8    8
[4,]    8    8
[5,]    2    2

【问题讨论】:

    标签: arrays r 3d apply


    【解决方案1】:

    尝试改用 which 函数

    res <- cbind(rep(0,5), rep(0,5))          #is the result matrix
    count <- 1                            #is the dimension count of the array
    while (count <= dim(arr)[3]){
        for (i in 1:nrow(arr[,,count])){
            res[i,count] <- sum(arr[i,c(which(arr[i,,count] != nul[i])), count])
        }
        count <- count + 1
    }
    

    但是我不明白最终的输出部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2017-03-15
      相关资源
      最近更新 更多