【问题标题】:Is there an R function to go from monthly to daily data by repeating the monthly value every day?是否有一个 R 函数可以通过每天重复每月值来从每月数据到每日数据?
【发布时间】:2020-06-09 00:27:20
【问题描述】:

假设我有一个月利率。我想将此信息表示为“每日”利率,并让每月利率每天重复,直到下个月更新。目的是为了每日报告,利率是指标之一。

假设我的日期列是年-日-月...

df.int = data.frame(c('2020-01-01','2020-01-02','2020-01-03','2020-01-04'),
                    c(0.02321,0.02198,0.01985,0.02011))

colnames(df.int) = c('Date','Interest Rate')

有什么建议可以解决这个问题吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以创建所需长度的每日日期范围,然后根据这些日期的月份加入该范围:

    library(lubridate)
    library(tidyverse)
    
    #convert Date to Date and create month variable
    df.int <- df.int %>% 
      mutate(Date = ydm(Date),
             month = month(Date))
    
    #create daily sequence with min-max date range based on min/max date of df.int$Date
    daily_df <- tibble(date = seq(min(df.int$Date), max(df.int$Date), "days")) %>% 
      mutate(month = month(date))
    
    #join based on month
    daily_df %>% 
      left_join(df.int, "month") %>% 
      select(-date)
    
    # A tibble: 92 x 3
       month Date       `Interest Rate`
       <dbl> <date>               <dbl>
     1     1 2020-01-01          0.0232
     2     1 2020-01-01          0.0232
     3     1 2020-01-01          0.0232
     4     1 2020-01-01          0.0232
     5     1 2020-01-01          0.0232
     6     1 2020-01-01          0.0232
     7     1 2020-01-01          0.0232
     8     1 2020-01-01          0.0232
     9     1 2020-01-01          0.0232
    10     1 2020-01-01          0.0232
    # ... with 82 more rows
    

    数据

    df.int = data.frame(c('2020-01-01','2020-01-02','2020-01-03','2020-01-04'),
                        c(0.02321,0.02198,0.01985,0.02011))
    
    colnames(df.int) = c('Date','Interest Rate')
    

    【讨论】:

      【解决方案2】:

      经过更多研究,我找到了这个帖子,回答了我的问题!

      Converting Monthly Data to Daily in R

      【讨论】:

        猜你喜欢
        • 2021-06-19
        • 2021-01-08
        • 1970-01-01
        • 2020-09-19
        • 1970-01-01
        • 2012-12-08
        • 2012-02-24
        • 2013-05-02
        • 2015-10-31
        相关资源
        最近更新 更多