如何从数组中删除NAs

huangapple go评论52阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月19日 11:41:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定