如果我有一个二维数组:
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,1
和2,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
谢谢
答案 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))