【问题标题】:Data transformation for time series时间序列的数据转换
【发布时间】:2020-06-07 22:17:03
【问题描述】:

这是我的实际数据集的示例:

library("tidyverse")
year <- c(2015,2015,2015,2016,2016,2016,2016)
period <- c("P1","P2","P3","P1","P2","P3","P4")
value <- c(120,130,25,114,236,541,248)
dete <- as.tibble(data.frame(year = year,periode = period, value = value))

所以,在这个数据集中,我们有: 年……年, 期间,就像一个月(相当于 12 周中的 4 周) 价值,例如一些销售价值

我的问题如下: 我想在输出中显示一个像这样向我显示每年的最大值(值)的小标题:

result <- as.tibble(data.frame(period = c("P1","P2","P3","P4"), occurence = c(0,1,1,0)))

但我也想增加权重,在这种情况下,2016 年有 12 个时期中有 4 个时期(一年中有 12 个月),而 2015 年只有 3 个时期。适当的结果是:

result <- as.tibble(data.frame(period = c("P1","P2","P3","P4"), occurence = c(0,3/12,4/12,0)))

通常我有 12 个时期,但有时在去年我只有一部分可用。

【问题讨论】:

    标签: r time time-series


    【解决方案1】:

    你说:

    我想在输出中显示一个小标题,显示每年的最大值(值)...按每年的周期数加权。

    所以我假设你想要这个:

    dete %>%
      group_by(year) %>%
      mutate(n=n()) %>%
      summarise(max.value=max(value), weight=mean(n) / 12, 
                occurrence=max.value*weight) %>%
      select(-max.value, -weight) # Optional
    

    # A tibble: 2 x 4
       year max.value weight occurence
      <dbl>     <dbl>  <dbl>     <dbl>
    1  2015       130  0.25       32.5
    2  2016       541  0.333     180. 
    

    我不明白为什么当你提到你想要的年份时输出中有句号。

    【讨论】:

    • 我错了,我想要一个 tibble,显示每个时期的最大次数。想象一下,我有一个 8 年的数据集,P2 中的值是我想在 P2 前面拥有的最大 8 次 -> 8。问题是:如果第 8 个值是一年只有 6 个时期,我不想要8 但 7.5
    【解决方案2】:

    不完全是你的输出,

    dete %>% 
      group_by(year) %>% 
      mutate(occurence_weighted = n() /12,
             max_occurance = paste0("P", max(as.numeric(gsub("P","",periode)))))
    

    会给你

     year periode value occurence_weighted max_occurance
      <dbl> <fct>   <dbl>              <dbl> <chr>        
    1  2015 P1        120              0.25  P3           
    2  2015 P2        130              0.25  P3           
    3  2015 P3         25              0.25  P3           
    4  2016 P1        114              0.333 P4           
    5  2016 P2        236              0.333 P4           
    6  2016 P3        541              0.333 P4           
    7  2016 P4        248              0.333 P4 
    

    删除多余的列会给你:

    dete %>% 
      group_by(year) %>% 
      mutate(occurence_weighted = n() /12,
             max_occurance = paste0("P", max(as.numeric(gsub("P","",periode))))) %>%
      select(year, occurence_weighted, max_occurance ) %>%
      distinct()
    
       year occurence_weighted max_occurance
      <dbl>              <dbl> <chr>        
    1  2015              0.25  P3           
    2  2016              0.333 P4  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-13
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多