英文:
How to remove NAs in an array
问题
考虑我们有一个数组:
tmp <- array(c(1, 2, 3, 4,
               NA, NA, NA, NA,
               5, 6, 7, 8), dim = c(2, 2, 3))
> print(tmp)
, , 1
     [,1] [,2]
[1,]    1    3
[2,]    2    4
, , 2
     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA
, , 3
     [,1] [,2]
[1,]    5    7
[2,]    6    8
在这里,我想移除包含 NA 的第二个矩阵。
当我们有一个矩阵时,使用 complete.cases 可以轻松移除包含 NA 的行。
tmp <- matrix(c(1, 2, NA, NA, 3, 4), ncol = 2, byrow = TRUE)
> print(tmp[complete.cases(tmp), ])
     [,1] [,2]
[1,]    1    2
[2,]    3    4
但是,在高维情况下,我不知道如何移除包含 NA 的元素。
英文:
Consider that we have an array:
tmp <- array(c(1, 2, 3, 4,
               NA, NA, NA, NA,
               5, 6, 7, 8), dim = c(2, 2, 3))
> print(tmp)
, , 1
     [,1] [,2]
[1,]    1    3
[2,]    2    4
, , 2
     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA
, , 3
     [,1] [,2]
[1,]    5    7
[2,]    6    8
Here, I want to remove the second matrix with NAs.
When we have a matrix, it is not hart to remove a row with NAs using the complete.cases
tmp <- matrix(c(1, 2, NA, NA, 3, 4), ncol = 2, byrow = TRUE)
> print(tmp[complete.cases(tmp), ])
     [,1] [,2]
[1,]    1    2
[2,]    3    4
But, in higher dimensional cases, I have no idea how to remove the NAs
答案1
得分: 2
apply在第3维度上应用,然后进行子集操作:
tmp[,,apply(tmp, 3, \(x) !all(is.na(x)) )]
# , , 1
#
#     [,1] [,2]
# [1,]    1    3
# [2,]    2    4
#
# , , 2
#
#     [,1] [,2]
# [1,]    5    7
# [2,]    6    8
英文:
apply across the 3rd dimension, and then subset:
tmp[,,apply(tmp, 3, \(x) !all(is.na(x)) )]
#, , 1
#
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
#
#, , 2
#
#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论