【问题标题】:R : Finding minimum value on the basis of changing preceding and suceeding values in group by columnR:在逐列更改前后值的基础上找到最小值
【发布时间】:2019-12-09 20:48:46
【问题描述】:

添加可复制性:

  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)

)

如下所示,我有一个表,我想按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

如下所示,结果表应包含最少的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)。非常感谢您提前。

【问题讨论】:

    标签: r dplyr data.table reshape2


    【解决方案1】:

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

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

    【讨论】:

    • 或使用dplyr df %&gt;% group_by(product) %&gt;% mutate(price.new = cummin(price))
    【解决方案2】:

    这是数据框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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 2021-03-08
      相关资源
      最近更新 更多