【问题标题】:Simplify a cleaning process简化清洁过程
【发布时间】:2021-12-12 11:42:27
【问题描述】:

我有一个要清理的数据框。有一列价格包含异常值,我想使用分位数 85 对其进行清理,但不是针对整个数据帧进行测量,而是针对属于同一“neighbourghood_group”的每组记录进行测量。

我正在一件一件地做。首先,我从原始数据帧 (df.imp) 创建一个新数据帧 (df.Barajas),并通过我想用来计算分位数的 neighbourhood_group 对其进行过滤。然后我计算特定 neighbourhood_group 的分位数,然后从原始文件中删除满足条件的行。

df.Barajas <- df.imp[df.imp$neighbourhood_group=="Barajas",]

Barajas.quantile <- quantile(df.Barajas$price, probs=c(.85), na.rm=T)

df.imp <- df.imp[!df.imp$neighbourhood=="Barajas" & df.imp$price<Barajas.quantile,]

但是有 21 个不同的 neighbourhood_groups,所以我必须编写 63 行代码。我该如何简化呢?

提前致谢, 加布里埃尔

【问题讨论】:

  • 请通过将您的数据作为对象包含在问题中来使您的问题可重现。使用dput(df) 将数据框粘贴到问题中。这使得其他人更容易测试和验证解决方案。 minimal reproducible example 提供指导。

标签: r


【解决方案1】:

等待@Peter 要求的可重现示例,您可能可以这样做:

library(tidyverse)
df_new <- df_imp %>%
  group_by(neighbourhood_group) %>%
  filter(price < quantile(price, probs = c(0.85), na.rm = TRUE))
  ungroup()

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2013-07-01
    • 2011-12-26
    相关资源
    最近更新 更多