NA 在尝试总结数据子集时 (R)

NA when trying to summarize a subset of data (R)

整个向量都可以,没有NAs:

> summary(data$marks)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    6.00    6.00    6.02    7.00    7.00

> length(data$marks)
[1] 2528

但是,当尝试使用标准计算子集时,我收到很多 NAs:

> summary(data[data$student=="John",]$marks)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
  1.000   6.000   6.000   6.169   7.000   7.000     464

> length(data[data$student=="John",]$marks)
[1] 523

我认为问题在于您缺少 student 的值。因此,当您按 student 进行子集化时,学生的所有 NA 值最终都会为 marks 生成 NA,当您获取子集时。将子集条件包装在 which() 中以避免此问题。以下是一些示例,希望能阐明正在发生的事情:

# Fake data
set.seed(103)
dat = data.frame(group=rep(LETTERS[1:3], each=3), 
                 value=rnorm(9))
dat$group[1] = NA

dat$value
dat[dat$group=="B", "value"]
dat[which(dat$group=="B"), "value"]

# Simpler example
x = c(10,20,30,40, NA)

x>20
x[x>20]

which(x>20)
x[which(x>20)]

首先请注意,NA=="foo" 结果为 NA。当用 NA 值对向量进行子集化时,结果为 NA。

t = c(1,2,3)
t[c(1,NA)]

一个tidyverse解决方案。我发现这些比基础 R 更容易阅读。

library(tidyverse)

data %<%
  filter(student == "John") %<%
  summary(marks)