我想要求ho将每个面板数据模型估算器中所有实际值和拟合值的日期变量包括在数据框中。
使用以下代码时:
library(plm)
library(dplyr)
YEAR <- c(2015, 2016, 2017, 2018,
2015, 2016, 2017, 2018,
2015, 2016, 2017, 2018,
2015, 2016, 2017, 2018)
YEAR <- as.Date(YEAR)
UNIT <- c("A", "A", "A", "A",
"B", "B", "B", "B",
"C", "C", "C", "C",
"D", "D", "D", "D")
Y <- sample(100:1000, 16)
X1 <- sample(10:50, 16)
X2 <- sample(20:60, 16)
data <- data.frame(YEAR, UNIT, Y)
crime.p <- pdata.frame(data,index=c("UNIT","YEAR"))
fixedeff <- plm(log(Y)~X1 + X2,data=crime.p,model="within")
randomeff <- plm(log(Y)~X1 +X2,data=crime.p,model="random")
firstdiff <- plm(log(Y)~X1 + X2,data=crime.p,model="fd")
fixx_results <- data.frame(fitted = predict(fixedeff),
residuals = fixedeff$residuals ) %>%
mutate( actual = fitted + residuals, model = "fixed" ) %>%
select(actual, model, fitted, residuals)
random_results <- data.frame( fitted = predict(randomeff), residuals = randomeff$residuals ) %>%
mutate( actual = fitted + residuals, model = "random" ) %>%
select(actual, model, fitted, residuals)
fd_results <- data.frame( fitted = predict(firstdiff ), residuals = firstdiff $residuals ) %>%
mutate( actual = fitted + residuals, model = "fd" ) %>%
select(actual, model, fitted, residuals)
fitted_res_all <- rbind(fixx_results, random_results, fd_results)
fitted_res_all
fitted_res_all
数据框不包含日期变量,我不知道如何在其中添加日期。我知道它可以“手工”完成,但我希望它尽可能通用,以便将来可以重用。
问题还在于每个面板数据估计量具有不同数量的观察值。 我要结束的是一个实际的和拟合的时间序列图,但在X轴上具有可变的日期,在此数据集中,我们有早期的数据,但有时他会有每月的数据。
答案 0 :(得分:0)
在数据框中添加日期应该可以解决您的问题
fixx_results <- data.frame(fitted = predict(fixedeff),
residuals = fixedeff$residuals, date = rownames(crime.p)) %>%
mutate( actual = fitted + residuals, model = "fixed" ) %>%
select(actual, model, fitted, residuals, date)
random_results <- data.frame( fitted = predict(randomeff), residuals = randomeff$residuals, date = rownames(crime.p)) %>%
mutate( actual = fitted + residuals, model = "random" ) %>%
select(actual, model, fitted, residuals, date)
fd_results <- data.frame( fitted = predict(firstdiff), residuals = firstdiff $residuals, date = rownames(crime.p)[4:length(crime.p)] ) %>%
mutate( actual = fitted + residuals, model = "fd" ) %>%
select(actual, model, fitted, residuals, date) ```