简体   繁体   English

将时间序列转换为data.frame,而不会丢失年和月项目

[英]Convert time series to data.frame without losing the year and Month items

I have a time series, dt_ts. 我有一个时间序列dt_ts。 I want to convert to dataframe without loosing the year and month 我想转换为数据框而不损失年份和月份

       Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
2005 41.26 40.02 38.24 35.37 39.35 38.90 43.51 40.32 38.14 41.04 41.78 40.48
2006 40.55 42.15 42.30 39.93 38.12 35.79 34.71 34.29 36.27 37.33 37.97 40.16
2007 40.74 39.59 36.74 37.87 38.87 39.35 37.17 38.31 32.44

I want something like: 我想要类似的东西:

Year Month Sales
2005 Jan    41.26
etc   etc    etc

A solution using dplyr , tidyr , and tibble . 使用A溶液dplyrtidyr ,和tibble

library(dplyr)
library(tidyr)
library(tibble)

dt2 <- dt %>%
  rownames_to_column("Year") %>%
  gather(Month, Sales, -Year) %>%
  mutate(Month = factor(Month, levels = colnames(dt))) %>%
  arrange(Year, Month)
dt2
   Year Month Sales
1  2005   Jan 41.26
2  2005   Feb 40.02
3  2005   Mar 38.24
4  2005   Apr 35.37
5  2005   May 39.35
6  2005   Jun 38.90
7  2005   Jul 43.51
8  2005   Aug 40.32
9  2005   Sep 38.14
10 2005   Oct 41.04
11 2005   Nov 41.78
12 2005   Dec 40.48
13 2006   Jan 40.55
14 2006   Feb 42.15
15 2006   Mar 42.30
16 2006   Apr 39.93
17 2006   May 38.12
18 2006   Jun 35.79
19 2006   Jul 34.71
20 2006   Aug 34.29
21 2006   Sep 36.27
22 2006   Oct 37.33
23 2006   Nov 37.97
24 2006   Dec 40.16
25 2007   Jan 40.74
26 2007   Feb 39.59
27 2007   Mar 36.74
28 2007   Apr 37.87
29 2007   May 38.87
30 2007   Jun 39.35
31 2007   Jul 37.17
32 2007   Aug 38.31
33 2007   Sep 32.44
34 2007   Oct    NA
35 2007   Nov    NA
36 2007   Dec    NA

DATA 数据

dt <- read.table(text = " Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
2005 41.26 40.02 38.24 35.37 39.35 38.90 43.51 40.32 38.14 41.04 41.78 40.48
2006 40.55 42.15 42.30 39.93 38.12 35.79 34.71 34.29 36.27 37.33 37.97 40.16
2007 40.74 39.59 36.74 37.87 38.87 39.35 37.17 38.31 32.44",
                 header = TRUE, fill = TRUE)

One option would be to convert to xts , get the 'index', split it into two column and cbind with vector 'ts1' 一种选择是转换为xts ,获取“索引”,将其分为两列,并与vector “ ts1” cbind

library(xts)
cbind(read.table(text = as.character(index(as.xts(ts1))), 
                   col.names = c('Month', 'Year')), Sales = c(ts1))

data 数据

set.seed(24)
ts1 <- ts(sample(50), start = c(2001, 1), frequency = 12)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM