如何从数组中删除NAs

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

How to remove NAs in an array

问题

考虑我们有一个数组:

  1. tmp <- array(c(1, 2, 3, 4,
  2. NA, NA, NA, NA,
  3. 5, 6, 7, 8), dim = c(2, 2, 3))
  4. > print(tmp)
  5. , , 1
  6. [,1] [,2]
  7. [1,] 1 3
  8. [2,] 2 4
  9. , , 2
  10. [,1] [,2]
  11. [1,] NA NA
  12. [2,] NA NA
  13. , , 3
  14. [,1] [,2]
  15. [1,] 5 7
  16. [2,] 6 8

在这里,我想移除包含 NA 的第二个矩阵。

当我们有一个矩阵时,使用 complete.cases 可以轻松移除包含 NA 的行。

  1. tmp <- matrix(c(1, 2, NA, NA, 3, 4), ncol = 2, byrow = TRUE)
  2. > print(tmp[complete.cases(tmp), ])
  3. [,1] [,2]
  4. [1,] 1 2
  5. [2,] 3 4

但是,在高维情况下,我不知道如何移除包含 NA 的元素。

英文:

Consider that we have an array:

  1. tmp <- array(c(1, 2, 3, 4,
  2. NA, NA, NA, NA,
  3. 5, 6, 7, 8), dim = c(2, 2, 3))
  4. > print(tmp)
  5. , , 1
  6. [,1] [,2]
  7. [1,] 1 3
  8. [2,] 2 4
  9. , , 2
  10. [,1] [,2]
  11. [1,] NA NA
  12. [2,] NA NA
  13. , , 3
  14. [,1] [,2]
  15. [1,] 5 7
  16. [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

  1. tmp <- matrix(c(1, 2, NA, NA, 3, 4), ncol = 2, byrow = TRUE)
  2. > print(tmp[complete.cases(tmp), ])
  3. [,1] [,2]
  4. [1,] 1 2
  5. [2,] 3 4

But, in higher dimensional cases, I have no idea how to remove the NAs

答案1

得分: 2

apply在第3维度上应用,然后进行子集操作:

  1. tmp[,,apply(tmp, 3, \(x) !all(is.na(x)) )]
  2. # , , 1
  3. #
  4. # [,1] [,2]
  5. # [1,] 1 3
  6. # [2,] 2 4
  7. #
  8. # , , 2
  9. #
  10. # [,1] [,2]
  11. # [1,] 5 7
  12. # [2,] 6 8
英文:

apply across the 3rd dimension, and then subset:

  1. tmp[,,apply(tmp, 3, \(x) !all(is.na(x)) )]
  2. #, , 1
  3. #
  4. # [,1] [,2]
  5. #[1,] 1 3
  6. #[2,] 2 4
  7. #
  8. #, , 2
  9. #
  10. # [,1] [,2]
  11. #[1,] 5 7
  12. #[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:

确定