有关缺失数据的问题

6 r matrix na

在矩阵中,如果有一些丢失的数据记录为"NA".

  • 我怎么能删除NA矩阵中的行?
  • 我可以用na.rm吗?

Mat*_*ker 6

na.omit()将采用矩阵(和数据框)并仅返回那些没有NA值的行 - 它complete.cases()更进一步为您删除FALSE行.

> x <- data.frame(c(1,2,3), c(4, NA, 6))
> x
  c.1..2..3. c.4..NA..6.
1          1           4
2          2          NA
3          3           6
> na.omit(x)
  c.1..2..3. c.4..NA..6.
1          1           4
3          3           6
Run Code Online (Sandbox Code Playgroud)


jon*_*mon 5

我认为na.rm通常只适用于函数,比如平均函数.我会选择complete.cases:http://stat.ethz.ch/R-manual/R-patched/library/stats/html/complete.cases.htm

假设你有以下3x3矩阵:

x <- matrix(c(1:8, NA), 3, 3)

> x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6   NA
Run Code Online (Sandbox Code Playgroud)

然后你可以得到这个矩阵的完整案例

y <- x[complete.cases(x),]

> y
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
Run Code Online (Sandbox Code Playgroud)

complete.cases -函数返回一个说的情况是否是完整的真值向量:

> complete.cases(x)
[1]  TRUE  TRUE FALSE
Run Code Online (Sandbox Code Playgroud)

然后索引矩阵x的行并添加","以表示您想要所有列.


Jos*_*ich 1

如果要删除包含 NA 的行,可以使用 apply() 应用快速函数来检查每一行。例如,如果你的矩阵是 x,

goodIdx <- apply(x, 1, function(r) !any(is.na(r)))
newX <- x[goodIdx,]
Run Code Online (Sandbox Code Playgroud)