【问题标题】:Why am I getting an NA when calculating the mean?为什么我在计算平均值时会得到 NA?
【发布时间】:2020-02-02 02:09:48
【问题描述】:

每次我尝试计算这一行“DHS

setwd("~/Google Drive/R Data")
data <- read.csv('cps92_08.csv')
year <- data$year
year1992 <- subset(data,year<2000)
year2008 <- subset(data,year>2000)
ahe1992 <- (year1992$ahe)
ahe2008 <- (year2008$ahe)
max(ahe1992)
min(ahe1992)
mean(ahe1992)
median(ahe1992)
sd(ahe1992)
max(ahe2008)
min(ahe2008)
mean(ahe2008)
median(ahe2008)
sd(ahe2008)

adjahe <- ahe1992*(215.2/140.3)
max(adjahe)
min(adjahe)
mean(adjahe)
median(adjahe)
sd(adjahe)

D <- mean(ahe2008) - mean(adjahe)

education <- data$bachelor
ahebachelors1992 <- subset(adjahe, education>0)
ahehighschool1992 <- subset(adjahe,education<1)
ahebachelors2008 <- subset(ahe2008,education>0)
ahehighschool2008 <- subset(ahe2008,education<1)

DHS <- mean(ahebachelors2008) - mean(ahebachelors1992)

【问题讨论】:

  • ahebachelors2008 中有什么内容?里面有NA吗?运行which(is.na(ahebachelors2008))?或者可能什么都没有?
  • 您的数据框中可能有 NA,您应该在计算 mean 时使用参数 na.rm = TRUE。检查文档?mean()
  • 请让这个问题可重现。这包括样本明确数据(例如,dput(head(x))data.frame(x=...,y=...))和预期输出。参考:stackoverflow.com/questions/5963269stackoverflow.com/help/mcvestackoverflow.com/tags/r/info
  • in ahebachelors2008 是 2008 年计算具有学士学位的人的平均小时收入的数据。如果我没有正确回答您的问题,我很抱歉,我两周前才开始使用 R,所以这对我来说太新鲜了!有什么我可以与您分享的信息可以帮助您更好地帮助我吗?我运行了函数 which(is.na(ahehbachelors2008)) 那里有 6594 个数据点。
  • 好吧,所以我刚刚检查了整个 ahbachelors 2008 并注意到在 6594 个数据点中,有 2953 个带有数字 --- 其余的都包含 NA。我将如何解决这个问题?

标签: r


【解决方案1】:

educationdata 的长度相同,而ahe2008data 的子集。因此,当您将 education 作为 ahe2008 的条件传递时,它会创建 NA(因为这是 ahe2008 中这些元素的对应值。

这是一个更简单的例子:

d1<-c(1:5)
d2<-c(1:5,1:5)
subset(d1,d2==1)
[1]  1 NA

可能的解决方案是为每年创建单独的 bachelor 向量,或者不连续子集,而只是在需要它们的地方使用多个条件。

如果您想避免每次都输入完整的data$something,请考虑使用with(),甚至更好——dplyr 包。

例如,最后一行之前的所有代码都可以用这个替换(假设我没有遗漏任何内容):

DHS <- mean(with(data,ahe[year>2000 & education>0])) - 
       mean(with(data,ahe[year<2000 & education>0]*(215.2/140.3))

(如果您是 R 新手,请注意 [] 结构是调用子集的更简单方法)。

您可能还想考虑使用summary,它将为您提供最小值、中值、平均值和最大值,而您只需手动添加sd。:

summary(with(data,ahe[year>2000]))

【讨论】:

  • 非常感谢您的评论!你能帮我举一个使用多个条件的例子吗?我将如何在 R 上制定它?
  • @sakina 请参阅上面的扩展答案。
  • 天哪!非常感谢你。这是我在 stackoverflow 上的第一篇文章,我不太确定是否能够获得帮助!太感谢了!我一定会四处寻找对我未来的帖子发表评论的“iod”。
【解决方案2】:

如果您尝试计算 mean 的值包含 NA,则输出将为 NA。您可以通过添加na.rm = TRUE 来克服它:

DHS <- mean(ahebachelors2008, na.rm=TRUE) - mean(ahebachelors1992, na.rm=TRUE)

【讨论】:

    猜你喜欢
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    相关资源
    最近更新 更多