繁体   English   中英

如何在搜寻最大值和最小值时排除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。

您可以像这样使用dplyr

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

这管用吗?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM