1
votes

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.

I tried it this way with DT (For maxValue everything works perfect):

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. 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.

In the best case I would like to have to dfs maxvalue and minvalue for each product.

3

3 Answers

3
votes

You can use dplyr like:

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

Using base R

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

Or with 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))
2
votes

Is this working?

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