Expanding R Matrix on Date

扶醉桌前 提交于 2021-02-10 20:01:45

问题


I have the following R matrix:

Date MyVal
2016  1
2017  2
2018  3
....
2026  10

What I want to do is "blow it up" so that it goes like this (where monthly values are linearly interpolated):

Date        MyVal
01/01/2016    1
02/01/2016    ..
....
01/01/2017    2
....
01/01/2026    10

I realize I can easily generate the sequence using:

DateVec <- seq(as.Date(paste(minYear,"/01/01", sep = "")), as.Date(paste(maxYear, "/01/01", sep = "")), by = "month")

And I can use that to make a large matrix and then fill things in using a for loop over the DateVector in but I wonder if there's a more elegant R way to do this?


回答1:


You can use stats::approx:

library(stats)

ipc <- approx(df$Date, df$MyVal, xout = DateVec, 
rule = 1, method = "linear", ties = mean)

You probably need to first convert the data in your original data-frame to have month and day and also be in asPOSIXct or as.Date format.

Based on what you provided, this works:

#Make the reference data-frame for interpolation:
DateVec <- seq(min(df$Date, na.rm=T), 
               max(df$Date, na.rm=T), by = "month")

#Interpolation:
intrpltd_df <- approx(df$Date, df$MyVal, xout = DateVec, 
          rule = 1, method = "linear", ties = mean)

#            x        y 
# 1 2016-01-01 1.000000 
# 2 2016-02-01 1.084699 
# 3 2016-03-01 1.163934 
# 4 2016-04-01 1.248634 
# 5 2016-05-01 1.330601 
# 6 2016-06-01 1.415301

Data:

#reproducing the data-frame:
Date <- seq(2016,2026)
MyVal <- seq(1:11)
Date <- data.frame(as.Date(paste0(Date,"/01/01"))) #yyyy-mm-dd format
df <- cbind(Date, MyVal)
df <- as.data.frame(df)
colnames(df) <- c ("Date", "MyVal") #Changing Column Names


来源:https://stackoverflow.com/questions/44273380/expanding-r-matrix-on-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!