如何在搜索最大值和最小值时排除 0?

How to exclude 0 in the search for the max and min values?

我有一个包含一些价格值的数据框。不,我想要一个或最好的情况是两个数据框,每篇文章的最大值和最小值不为 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。

这有效吗?

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

您可以使用 dplyr 如:

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

使用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))