如何将2个时间序列数据(宽表)合并为1个数据框(宽表)?
我使用RStudio
,我有以下从我R
码2个输出:如何将2个时间序列数据(宽表)合并为1个数据框(宽表)?
actual_2017 <- tail(mydata,12) > actual_2017
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2017 5980 5341 5890 5596 5753 5470 5589 5545 5749 5938 5844 5356
> predicted_2017 <- head(pred1,12)
> predicted_2017
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2017 5762 5275 5733 5411 5406 4954 5464 5536 5805 5819 5903 5630
> str(actual_2017)
Time-Series [1:12] from 2017 to 2018: 5980 5341 5890 5596 5753 5470 5589 5545 5749 5938 ...
> str(predicted_2017)
Time-Series [1:12] from 2017 to 2018: 5763 5275 5734 5412 5407 ...
我要合并actual_2017
和predicted_2017
成数据帧,但保持该宽表格格式。
比方说,这是该数据帧后我:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2017(A) 5980 5341 5890 5596 5753 5470 5589 5545 5749 5938 5844 5356
2017(P) 5762 5275 5733 5411 5406 4954 5464 5536 5805 5819 5903 5630
我怎样才能做到这一点?另外,2017年之前我需要(A)和(P),以便表格清楚了解其内容。
回答:
使用,t
(转),rbind
,names
,rownames
等就可以实现你想要什么:
actual_2017 <- data.frame(t(c(5980, 5341, 5890, 5596, 5753, 5470, 5589, 5545, 5749, 5938, 5844, 5356))) names(actual_2017) <- c("Jan", "Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
rownames(actual_2017) <- "2017"
actual_2017
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2017 5980 5341 5890 5596 5753 5470 5589 5545 5749 5938 5844 5356
predicted_2017 <- data.frame(t(c(5762, 5275, 5733, 5411, 5406, 4954, 5464, 5536, 5805, 5819, 5903, 5630)))
names(predicted_2017) <- c("Jan", "Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
rownames(predicted_2017) <- "2017"
predicted_2017
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2017 5762 5275 5733 5411 5406 4954 5464 5536 5805 5819 5903 5630
merged <- rbind(actual_2017, predicted_2017)
rownames(merged) <- c("2017 (A)", "2017 (P)")
merged
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2017 (A) 5980 5341 5890 5596 5753 5470 5589 5545 5749 5938 5844 5356
2017 (P) 5762 5275 5733 5411 5406 4954 5464 5536 5805 5819 5903 5630
回答:
希望这有助于!
#sample data (I cooked my own sample data, hope you don't mind it!) actual_2017 <- ts(tail(AirPassengers,12), start = 2017, frequency = 12)
predicted_2017 <- ts(head(AirPassengers, 12), start = 2017, frequency = 12)
#merge both timeseries data
df <- rbind(actual_2017, predicted_2017)
colnames(df) <- month.abb
rownames(df) <- gsub("(^\\w).*(\\d{4}$)","\\2 (\\1)",rownames(df))
df
输出是:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2017 (a) 417 391 419 461 472 535 622 606 508 461 390 432
2017 (p) 112 118 132 129 121 135 148 148 136 119 104 118
以上是 如何将2个时间序列数据(宽表)合并为1个数据框(宽表)? 的全部内容, 来源链接: utcz.com/qa/261268.html