-1

我想将自定义函数应用于 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
4

1 回答 1

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
}

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

于 2013-09-14T15:42:35.710 回答