[英]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.