【问题标题】:How to exclude 0 in the search for the max and min values?如何在搜索最大值和最小值时排除 0?
【发布时间】:2019-08-18 21:31:44
【问题描述】:

我有一个包含一些价格值的数据框。不,我希望有一个或最好是两个数据框,每篇文章的最大值和最小值都没有 0。

我用 DT 尝试过这种方式(对于 maxValue,一切正常):

minValue <- setDT(df)[, .SD[which.min(price > 0)], by=number]
maxValue <- setDT(df)[, .SD[which.max(price)], by=number]

但 minValue Df 显示 0 值。我也试过了:

do.call(rbind, tapply(df$price, df$number, FUN = function(x) c(max = max(x), min = min(x))))

但是这里我不知道如何使用 > 0 条件。

在最好的情况下,我希望对每个产品都进行 dfs maxvalue 和 minvalue。

【问题讨论】:

    标签: r dataframe minmax


    【解决方案1】:

    这行得通吗?

      minValue <- setDT(df)[price!=0, .(MinPrice=min(price)), by=number]
      maxValue <- setDT(df)[price!=0, .(MaxPrice=max(price)), by=number]
    

    【讨论】:

      【解决方案2】:

      您可以使用dplyr 喜欢:

      library(dplyr)
      df %>%
        group_by(number) %>%
        filter(price != 0) %>%
        summarise(minPrice = min(price),
                  maxPrice = max(price))
      

      【讨论】:

        【解决方案3】:

        使用base R

        f1 <- function(x) c(minPrice = min(x), maxPrice = max(x))
        aggregate(price ~ number, FUN = f1, df, subset = price != 0))
        

        by

        do.call(rbind, by(df, df$number, FUN = f1))
        

        数据

        df <- data.frame(number = c(1, 1, 1, 2, 2, 3, 3, 3), 
                 price = c(0, 3, 2, 4, 3, 1, 2, 0))
        

        【讨论】:

          猜你喜欢
          • 2014-11-03
          • 1970-01-01
          • 2014-01-12
          • 2018-04-09
          • 1970-01-01
          • 2018-12-23
          • 2016-05-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多