19

我想尝试两件事:

  1. 如何删除包含 NA/NaN/Inf 的行
  2. 如何将数据点的值从 NA/NaN/Inf 设置为 0。

到目前为止,我已经尝试使用以下 NA 值,但收到警告。

> eg <- data[rowSums(is.na(data)) == 0,]
 Error in rowSums(is.na(data)) : 
       'x' must be an array of at least two dimensions
     In addition: Warning message:
     In is.na(data) : is.na() applied to non-(list or vector) of type 'closure'
4

4 回答 4

38

我想我会用我喜欢的方法把我的帽子扔进戒指:

# sample data
m <- matrix(c(1,2,NA,NaN,1,Inf,-1,1,9,3),5)
# remove all rows with non-finite values
m[!rowSums(!is.finite(m)),]
# replace all non-finite values with 0
m[!is.finite(m)] <- 0
于 2013-04-02T20:17:33.890 回答
13
library(functional)
m[apply(m, 1, Compose(is.finite, all)),]

示范:

m <- matrix(c(1,2,3,NA,4,5), 3)
m
##      [,1] [,2]
## [1,]    1   NA
## [2,]    2    4
## [3,]    3    5

m[apply(m, 1, Compose(is.finite, all)),]
##      [,1] [,2]
## [1,]    2    4
## [2,]    3    5

注: Compose(is.finite, all)相当于function(x) all(is.finite(x))

要将值设置为 0,请使用矩阵索引:

m[!is.finite(m)] <- 0
m
##      [,1] [,2]
## [1,]    1    0
## [2,]    2    4
## [3,]    3    5
于 2013-04-02T20:00:06.513 回答
9

NaRV.omit(x) 是我对问题 1 的首选选项。助记符 NaRV 的意思是“不是常规值”。

require(IDPmisc)
m <- matrix(c(1,2,3,NA,5, NaN, 7, 8, 9, Inf, 11, 12, -Inf, 14, 15), 5)
> m
     [,1] [,2] [,3]
[1,]    1  NaN   11
[2,]    2    7   12
[3,]    3    8 -Inf
[4,]   NA    9   14
[5,]    5  Inf   15
> NaRV.omit(m)
     [,1] [,2] [,3]
[1,]    2    7   12
attr(,"na.action")
[1] 1 3 4 5
attr(,"class")
[1] "omit"
于 2014-10-20T15:02:35.677 回答
4

只是另一种方式(对于第一个问题):

m <- structure(c(1, 2, 3, NA, 4, 5, Inf, 5, 6, NaN, 7, 8), 
              .Dim = c(4L, 3L))
#      [,1] [,2] [,3]
# [1,]    1    4    6
# [2,]    2    5  NaN
# [3,]    3  Inf    7
# [4,]   NA    5    8

m[complete.cases(m * 0), , drop=FALSE]
#      [,1] [,2] [,3]
# [1,]    1    4    6

除了马修对第二部分的回答之外,我想不出其他任何东西。

于 2013-04-02T20:10:18.370 回答