2017-05-30 25 views
1

擴大R矩陣我有以下的R矩陣:上日期

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

我想要做的是「炸燬」,所以它是這樣的(其中月度值線性插值):

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

我知道我可以使用易於生成序列:

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

而且我可以用它來製作一個大型矩陣然後在DateVector中使用for循環來填充內容,但我不知道是否有更優雅的R方法來執行此操作?

+0

看看'merge' – HubertL

+0

如果提供[重複的例子(HTTPS? ://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)我可以檢查它的解決方案。 – Masoud

+0

檢查下面的解決方案。同時,它需要根據數據集的確切結構進行一些修改(不是最後一行,而是數據框準備部分)。 – Masoud

回答

1

您可以使用stats::approx

library(stats) 

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

你可能需要先轉換數據在原始數據幀有月份和日期,並在asPOSIXctas.Date格式。

根據您所提供的東西,這個工程:

#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 

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

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

這是輸出:

> head(data.frame(intrpltd_df)) 

#   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