Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 从3D数组的行函数计算中排除特定行元素[r]_Arrays_R_3d_Apply - Fatal编程技术网

Arrays 从3D数组的行函数计算中排除特定行元素[r]

Arrays 从3D数组的行函数计算中排除特定行元素[r],arrays,r,3d,apply,Arrays,R,3d,Apply,我想对3d数组的每一行应用一个自定义函数,不包括存储在vector 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) 如您所见,

我想对3d数组的每一行应用一个自定义函数,不包括存储在vector 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)
如您所见,仅排除位置[1,1,1]处的“1”,而不是该行中的每个匹配值。此外,该函数不包括每行中的“1”,而不仅仅是第一行

所需输出为:

[1,]    2    2
[2,]    6    6
[3,]    8    8
[4,]    8    8
[5,]    2    2
请尝试使用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
}
res
[1,]    2    2
[2,]    6    6
[3,]    8    8
[4,]    8    8
[5,]    2    2
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
}