【问题标题】:getting rid of the certain columns in the loop摆脱循环中的某些列
【发布时间】:2022-01-22 09:13:32
【问题描述】:
outliers <- d_car_nb %>% 
  group_by(factor, segment) %>% 
  mutate(hinge_spread = 1.5*IQR(sold_fee), 
         lwr = quantile(sold_fee, .25) - hinge_spread, 
         upr = quantile(sold_fee, .75) + hinge_spread) %>%
  filter(sold_fee > upr | sold_fee < lwr)

outliers_sold_fee<-outliers %>%
  select(quotedate,factor,segment,sold_fee)
print(outliers_sold_fee)

我不知道如何循环遍历这个函数,以便每次都填写不同的 KPI,然后是 sold_fee 以及每次使用 (quotedate,factor,segment,'kpi') 获得新数据帧时

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。

标签: r


【解决方案1】:

解决方案的关键是调用dplyrfilter()select()函数,使引用变量的关键字使用SE进行评估(标准评估,即其中变量以字符串形式给出(例如"sold_fee",如在基础 R 中的 outliers[,"sold_fee"]),而不是 NSE(非标准评估,其中变量以不带引号的文本给出(例如 @ 987654327@ 与outliers$sold_fee 相同,基数为 R))(*)。

NSE 是在 dplyr 中定义的函数中的默认评估类型,它可以从存储在另一个变量中的值中引用变量(这是您创建所需循环所需要的随心所欲地工作)并不简单。

filter()select() 的文档中,我们推断它们各自使用 SE 的方式不同,如下:

filter() 中,我们应该使用.data 代词。在您的示例中,它将是:

v = "sold_fee"
filter(.data[[v]] > upr | .data[[v]] < lwr)

select() 中,我们应该使用all_of() 函数。在您的示例中,它将是:

v = "sold_fee"
select(quotedate, factor, segment, all_of(v))

也就是说,您现在可以调整您的代码,以便从包含您的分析变量的数组中读取 sold_fee 名称并对其进行循环。然后,您将使用上述filter()select() 的使用表格来获得您想要的。

最后,请注意,您可以将包含要根据异常值可视化的列的数据框的结果存储在列表中,然后在循环完成后一次性打印所有内容,如下所示:

library(dplyr)

vars4analysis = c("sold_fee")  # List all the variables you want to analyze for outliers here
outliers_info = list()
for (v in vars4analysis) {
  outliers = ...                         # filter command here
  outliers_info[[v]] = outliers %>% ...  # select command here
}
print(outliers_info)  # This will show the info about the outliers for each analysis variable

(*) 您可以在此处阅读有关非标准评估的更多信息:http://adv-r.had.co.nz/Computing-on-the-language.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    相关资源
    最近更新 更多