问题描述
我有以下R矩阵:
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")
我可以用它来制作一个大矩阵,然后在for中使用DateVector上的for循环来填充内容,但我想知道是否有更优雅的R方法可以做到这一点?
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?
推荐答案
您可以使用 stats :: approx
:
library(stats)
ipc <- approx(df$Date, df$MyVal, xout = DateVec,
rule = 1, method = "linear", ties = mean)
您可能首先需要将原始数据框中的数据转换为具有月份和日期的数据,并且还必须采用 asPOSIXct
或 as.Date
格式.
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
这篇关于在日期扩展R矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!