R:在按列更改前后值的基础上找到最小值

R : Finding minimum value on the basis of changing preceding and suceeding values in group by column

为可复制性添加:

  data.frame(
product=c(rep("x",2),rep("y",3)),
price_category_from=c(10,20,10,20,30),
price=c(30,31,31,30,27)

)

如下所示,我有一个 table,我想按 product 分组并更改 price_category_from 列的值以找到最小值 price

product     price_category_from     price
  x                10                30
  x                20                31
  y                10                31
  y                20                30
  y                30                27

如下所示,结果 table 应包含最小 price.new 列,用于更改 price_category_from 列中的值。例如,产品 x 两行中的 price.new30,因为 price_category_from 类别的后续 price 值更大。而对于产品 y,每个后续 price_category_from 类别的最小值都会发生变化,因为接下来的 price 值较小。

price_category_from中的值是递增顺序的区间。

product     price_category_from     price    price.new
  x                10                30        30
  x                20                31        30  **
  y                10                31        31
  y                20                30        30
  y                30                27        27

我希望我能够解释这个问题。非常感谢您的帮助(最好是 data.table)。非常感谢你提前。

您可以使用 cummin 获得累积最小值(所有值的最小值直到给定值)

library(data.table)
setDT(df)

df[, price.new := cummin(price), by = product]

df
#    product price_category_from price price.new
# 1:       x                  10    30        30
# 2:       x                  20    31        30
# 3:       y                  10    31        31
# 4:       y                  20    30        30
# 5:       y                  30    27        27

或以 R 为基数

df$price.new <- with(df, ave(price, product, FUN = cummin))

这是数据框 df

base R 解决方案
df.out <- Reduce(rbind,lapply(split(df,df$product), 
                              function(x) within(x,price.new <- cummin(price))))

这样

> df.out
  product price_category_from price price.new
1       x                  10    30        30
2       x                  20    31        30
3       y                  10    31        31
4       y                  20    30        30
5       y                  30    27        27

数据

df <- structure(list(product = structure(c(1L, 1L, 2L, 2L, 2L), .Label = c("x", 
"y"), class = "factor"), price_category_from = c(10L, 20L, 10L, 
20L, 30L), price = c(30L, 31L, 31L, 30L, 27L)), class = "data.frame", row.names = c(NA, 
-5L))