如果不满足某些条件,则将多维数组中的所有值设置为0

时间:2019-11-25 22:56:27

标签: r arrays

如果我有一个二维数组:

创建两个不同长度的向量。

vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)

# Take these vectors as input to the array.
result <- array(c(vector1,vector2),dim = c(3,3,2))

result
, , 1

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   5    14
[3,]    3   12   15

, , 2

     [,1] [,2] [,3]
[1,]    7   8    14
[2,]    9   7    14
[3,]    1   12   22

如果result[,,1] != 5中的值和result[,,2] =! 7中的值,如何将2d数组中的所有值设置为0。也就是说,应该仅保留两个值-1,12,2,这样我就剩下了:

result
, , 1

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

, , 2

     [,1] [,2] [,3]
[1,]    7   0    0
[2,]    0   7    0
[3,]    0   0    0

谢谢

1 个答案:

答案 0 :(得分:1)

创建一个逻辑表达式,根据第三维的replicate将其array转换为length并乘以(*

i1 <- ((result[,,1] == 5)|(result[,,2] == 7))
result * replicate(dim(result)[3], i1)
#, , 1
#
#     [,1] [,2] [,3]
#[1,]    5    0    0
#[2,]    0    5    0
#[3,]    0    0    0

#, , 2

#     [,1] [,2] [,3]
#[1,]    7    0    0
#[2,]    0    7    0
#[3,]    0    0    0

或使用for循环

vals <- c(5, 7)
for(i in seq_len(dim(result)[3])) {
     result[,,i] <- result[,,i] *(result[,,i] == vals[i])
   }

数据

result <- array(c(5, 9, 3, 10, 5, 12, 13, 14, 15, 7, 9, 1, 8, 7, 
       12, 14, 14, 22), dim = c(3, 3, 2))