【问题标题】:rolling geometric means using dplyr and tbrf使用 dplyr 和 tbrf 滚动几何均值
【发布时间】:2018-09-28 15:34:34
【问题描述】:

我想使用 dplyr 和 tbrf 计算每组“类型”的 90 天滚动几何平均值和第 90 个百分位数。下面的代码为每个日期生成百分位数,而不是每 90 天。它也错误地生成了重复的行。

旁注:我首先尝试使用 %within% 并在 lubridate 包中创建一个间隔。但是,dplyr 目前不支持来自 lubridate 的类 Interval,因此想尝试 tbrf。我也试过 tibbletime、RcppRoll 和 zoo 的 Rollapply

##sample data###

Value=c(50,900,25,25,125,50,25,25,2000,25,25,
25,25,25,25,25,25,325,25,300,475,25)
Dates = as.Date(c("2015-02-23","2015-04-20","2015-06-17",
"2015-08-20","2015-10-05","2015-12-22",
"2016-01-19","2016-03-29","2016-05-03",
"2016-07-21","2016-09-08","2016-11-07",
"2017-02-27","2017-04-19","2017-06-29",
"2017-08-24","2017-10-23","2017-12-28",
"2018-01-16","2018-03-14","2018-05-29",
"2018-07-24"))
Type = c(rep("A", 11), rep("B", 11))

df=data.frame(Value,Dates,Type)



######failed attempt 1####
df2=df %>% group_by(Type) %>% 
 tbr_gmean(Value, Dates, "days", 90) %>%
  tbr_misc(Value, Dates,"days",  90, quantile, .(0.9)) 

 ## failed attempt #2##
 start.date = min(df$Dates)
 breaks = seq(start.date - 30*3600*24, start.date + 30*3600*24, "90 days")
 df$group = cut(df$Dates, breaks=breaks)
 DF= df %>% group_by(Type,group) %>% 
 mutate(Count=n(),gm=geoMean(Value),
 percentile_90=quantile(Value,0.90))

【问题讨论】:

  • 你查过代码as.Date(c(5:20))
  • 是的。它生成 16 个连续日期
  • 对我来说,它给出了错误as.Date(c(5:20))# Error in as.Date.numeric(c(5:20)) : 'origin' must be supplied
  • 你不是说Dates1 <- as.Date(Sys.Date() + 5:20)吗?
  • 很奇怪。我给你改一下

标签: r dplyr


【解决方案1】:

已编辑:试试这个:

library(psych)
library(dplyr)
library(zoo)
dfmod<-df %>% 
    group_by(Type) %>% 
      arrange(Dates) %>%
        mutate(rnk = cumsum(c(TRUE, diff(Dates) > 5)))%>% #changed it from !=1 to reflect that you want the date difference to be within 5 days or less
          group_by(Type,rnk) %>% 
            mutate(GM = rollapply(Value, 2, geometric.mean, fill=NA, align="right"),
                    qt=rollapply(Value, 2, quantile, p=0.90, fill=NA, align="right")) #changed 5 to 2 so that the rolling sum is calculated for every 2 rows 
 head(dfmod)
## A tibble: 6 x 6
## Groups:   Type, rnk [1]
#  Dates      Type  Value   rnk    GM    qt
#  <date>     <fct> <dbl> <int> <dbl> <dbl>
#1 2018-10-03 A      35.3     1  NA    NA  
#2 2018-10-04 A      34.3     1  NA    NA  
#3 2018-10-05 A      34.6     1  NA    NA  
#4 2018-10-06 A      34.3     1  NA    NA  
#5 2018-10-07 A      34.1     1  34.5  35.1
#6 2018-10-08 A      34.7     1  34.4  34.6

【讨论】:

  • @shum 我的编辑应该涵盖这些问题。希望它有效!
  • @shum 我以为你要编辑你的数据集?!
  • 将问题中的滚动期从 5 天更改为 90 天,并使用更实际的日期更新数据集....并且您的代码有效! @ShirinYavari
猜你喜欢
  • 2014-11-29
  • 2019-09-22
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
相关资源
最近更新 更多