【问题标题】:Lag based on condition基于条件的滞后
【发布时间】:2020-10-19 05:41:03
【问题描述】:

我有历史月度数据,需要进行滚动计算。每个时期的价格将与 3 年前的日期进行比较,即当前价格/基准价格。这里 Base 是 3 年过去的日期。它将在每个月滚动。每个月都应该比较 3 年粘贴日期。我正在使用lag 函数来查找过去的日期。它在 2013 年 1 月之前返回 NA,这是正确的。

我想添加其他标准 - 如果(位置、资产、子类型)的最小组合日期是 2010 年后,则应将其与组合的最小日期进行比较。例如,最低日期是 2014 年 1 月,因此 2014 年 1 月之后的所有价格都应与 2014 年 1 月(静态基准年)进行比较。

您可以从下面的代码中读取数据-

library(readxl)
library(httr)
GET("https://sites.google.com/site/pocketecoworld/Trend_Sale%20-%20Copy.xlsx", write_disk(tf <- tempfile(fileext = ".xlsx")))
dff <- read_excel(tf)

我的代码 -

dff <- dff %>% group_by(Location, Asset, SubType) %>% 
  mutate(BasePrice=lag(Price, 36), 
         Index = round(100*(Price/BasePrice), 1)) %>% 
  filter(Period >= '2013-01-31')

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你的意思是这样的吗?

    library(dplyr)
    
    dff %>%
      group_by(Location, Asset, SubType) %>% 
      mutate(BasePrice= if(lubridate::year(min(Period)) > 2010) 
                           Price[which.min(Period)] else lag(Price, 36), 
             Index = round(100*(Price/BasePrice), 1))
    

    如果Period 中的最小日期在 2010 年之后,我们选择最小 Period 值的 Price 或使用 3 年前的 Price 作为 BasePrice

    【讨论】:

    • 这是完美的。我们可以在选择组合的第一个非 NA 值 - 位置、资产、子类型的末尾放置一个过滤器吗?
    • 要获得组合中的第一个非 NA 值,您可以添加 slice(which(!is.na(Index))[1])
    • 刚刚意识到 - filter(!is.na(BasePrice)) 也可以在 group_by( ) 生效时工作
    猜你喜欢
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2013-05-15
    • 2020-02-18
    相关资源
    最近更新 更多