简体   繁体   English

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

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

I have a dataframe with some price values. 我有一个带有某些价格值的数据框。 No I want to have one or in best case two data frames with the max and min values for each article without 0 values. 不,我想为每个商品设置一个或最好两个数据框,最大和最小值不带0值。

I tried it this way with DT (For maxValue everything works perfect): 我用DT进行了这种尝试(对于maxValue,一切正常。):

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

But the minValue Df shows 0 Values. 但是minValue Df显示0个值。 I have also tried it with: 我也尝试过:

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

But here I dont know how to use the > 0 condition. 但是这里我不知道如何使用> 0条件。

In the best case I would like to have to dfs maxvalue and minvalue for each product. 在最好的情况下,我想必须为每个产品设置dfs maxvalue和minvalue。

You can use dplyr like: 您可以像这样使用dplyr

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

Is this working? 这管用吗?

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

Using base R 使用base R

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

Or with by by

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

data 数据

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