【问题标题】:use filter function within summarise function from dplyr在 dplyr 的汇总函数中使用过滤器函数
【发布时间】:2020-12-18 02:12:06
【问题描述】:

有没有办法在summary中使用过滤功能,例如:

#I have a dataset with 5 columns Price, Type, Amount USD, date 
# I only want the mean price of the rows that are not Type == "SELL"

data = summarise(Price = filter(!Type == "SELL") %>% mean(Price), Amount = sum(Amount), USD = sum(USD), date = min(date))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你可以使用:

    library(dplyr)
    
    data %>%
      summarise(Price = mean(Price[Type != 'SELL']), 
                Amount = sum(Amount), 
                USD = sum(USD), 
                date = min(date))
    

    在管道中使用它:

    data %>%
      summarise(Price = mean(data %>% filter(Type != 'SELL') %>% pull(Price)), 
                Amount = sum(Amount), 
                USD = sum(USD), 
                date = min(date))
    

    【讨论】:

    • 谢谢,所以确定不能在 summarise 函数中使用管道?
    • 是的,但我觉得这个任务非常复杂。查看更新的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2017-03-19
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多