【问题标题】:Looping through aggregated data in R循环遍历 R 中的聚合数据
【发布时间】:2017-02-28 14:02:34
【问题描述】:

我正在尝试在数据框特定列中估算缺失值。

我的意图是通过其他列的组来替换它。

我使用aggregate保存了汇总结果:

# Replace LotFrontage missing values by Neighborhood mean
lot_frontage_by_neighborhood = aggregate(LotFrontage ~ Neighborhood, combined, mean)

现在我想实现这样的东西:

for key, group in lot_frontage_by_neighborhood:
    idx = (combined["Neighborhood"] == key) & (combined["LotFrontage"].isnull())
    combined[idx, "LotFrontage"] = group.median() 

这当然是python代码。

不知道如何在 R 中实现这一点,有人可以帮忙吗?

例如:

Neighborhood  LotFrontage
     A            20
     A            30
     B            20
     B            50
     A           <NA>

NA 记录应替换为 25(Neighborhood A 中所有记录的平均 LotFrontage)

谢谢

【问题讨论】:

  • 你能提供预期输出的样本数据吗?
  • @count 添加,谢谢
  • require(dplyr); dat %&gt;% group_by(Neighborhood) %&gt;% mutate(LotFrontage = ifelse(is.na(LotFrontage ),mean(LotFrontage ,na.rm=TRUE),LotFrontage ))

标签: r dataframe aggregate na


【解决方案1】:

这是您正在寻找的想法吗?您可能需要 which() 函数来确定哪些行具有 NA 值。

set.seed(1)
Neighborhood = sample(letters[1:4], 10, TRUE)
LotFrontage = rnorm(10,0,1)
LotFrontage[sample(10, 2)] = NA

# This data frame has 2 columns. LotFrontage column has 10 missing values.
df = data.frame(Neighborhood = Neighborhood, LotFrontage = LotFrontage)

# Sets the missing values in the Neighborhood column to the mean of the LotFrontage values from the rows with that Neighborhood
x<-df[which(is.na(df$LotFrontage)),]$Neighborhood
f<-function(x) mean(df[(df$Neighborhood==x),]$LotFrontage, na.rm =TRUE)
df[which(is.na(df$LotFrontage)),]$LotFrontage <- lapply(x,f)

【讨论】:

  • 不完全是。假设我有 3 个邻域 A, B, C,以及记录 X,其中 LotFrontageNA,它的邻域是 B。我想用mean( all records which has neighborhood B ) 替换缺失值
  • 那么,LotFrontage 是定量变量,而街区是定性变量吗?
  • 是的,我在主帖中添加了一个示例。谢谢
  • 好的,我刚刚编辑了我的答案。这是你的想法吗?
  • 您好朋友,现在计算似乎可以了,但是之后的数据框看起来很奇怪。 head(combined$LotFrontage, n = 15) 在操作产生之前:[1] 65 80 68 60 84 85 75 NA 51 50 70 85 NA 91 NA,而之后它产生:[[1]] [1] 65 [[2]] [1] 80 [[3]] [1] 68 [[4]] [1] 60 [[5]] [1] 84 [[6]] [1] 85 [[7]] [1] 75 [[8]] [1] 81.51765 [[9]] [1] 51 [[10]] [1] 50 [[11]] [1] 70 [[12]] [1] 85 [[13]] [1] 74.55102 [[14]] [1] 91 [[15]] [1] 75.21067 为了解决我使用了sapply 而不是lapply
猜你喜欢
  • 1970-01-01
  • 2021-11-22
  • 2017-12-14
  • 1970-01-01
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
相关资源
最近更新 更多