我有一个时间序列,dt_ts。我想转换到dataframe而不会失去年份和月份
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
我想要类似的东西:
Year Month Sales
2005 Jan 41.26
etc etc etc
答案 0 :(得分:3)
使用dplyr
,tidyr
和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
数据强>
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)
答案 1 :(得分:1)
一种选择是转换为xts
,获取'索引',将其拆分为两列,cbind
转换为vector
'ts1'
library(xts)
cbind(read.table(text = as.character(index(as.xts(ts1))),
col.names = c('Month', 'Year')), Sales = c(ts1))
set.seed(24)
ts1 <- ts(sample(50), start = c(2001, 1), frequency = 12)