将时间序列数据从宽格式重塑为高格式(用于绘图) [英] Reshaping time series data from wide to tall format (for plotting)

查看:14
本文介绍了将时间序列数据从宽格式重塑为高格式(用于绘图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中包含多个时间序列的回报,存储在列中.

I have a data frame containing multiple time series of returns, stored in columns.

第一列包含日期,随后的列是独立的时间序列,每个都有一个名称.列标题是变量名.

The first column contains dates, and subsequent columns are independent time series each with a name. The column headers are the variable names.

## I have a data frame like this
t <- seq(as.Date('2009-01-01'),by='days',length=10)
X <- rnorm(10,0,1)
Y <- rnorm(10,0,2)
Z <- rnorm(10,0,4)

dat <- data.frame(t,X,Y,Z)

## which appears as
           t          X          Y         Z
1 2009-01-01 -1.8763317 -0.1885183 -6.655663
2 2009-01-02 -1.3566227 -2.1851226 -3.863576
3 2009-01-03 -1.3447188  2.4180249 -1.543931

我想将每个时间序列绘制为单独的图上的一条线,在一个格子中,每个图都由变量名称标记.

I want to plot each time series as a line on a separate plot, in a lattice, with each plot labeled by the variable names.

要使用格子绘制此图,数据必须采用高格式,例如:

To plot this with lattice, the data must be in a tall format, as such:

           t symbol       price
1 2009-01-01      X -1.8763317
2 2009-01-02      Y -0.1885183
2 2009-01-02      Z -6.655663

什么是一个好的函数调用来做到这一点?

What is a good function call to do this?

推荐答案

你也可以使用 'reshape' 库中的 melt() (我认为它比 reshape() 本身更容易使用) - 这将为你节省必须在...中添加时间列的额外步骤...

you can also use melt() from the 'reshape' library (I think it's easier to use than reshape() itself) - that'll save you the extra step of having to add the time column back in...

> library(reshape)
> m <- melt(dat,id="t",variable_name="symbol")
> names(m) <- sub("value","price",names(m))
> head(m)
           t symbol       price
1 2009-01-01      X -1.14945096
2 2009-01-02      X -0.07619870
3 2009-01-03      X  0.01547395
4 2009-01-04      X -0.31493143
5 2009-01-05      X  1.26985167
6 2009-01-06      X  1.31492397
> class(m$t)
[1] "Date"
> library(lattice)                                                              
> xyplot( price ~ t | symbol, data=m ,type ="l", layout = c(1,3) )

但是,对于这个特定的任务,我会考虑使用动物园"库,它不需要您重塑数据框:

For this particular task, however, I would consider using the 'zoo' library, which would not require you to reshape the data frame:

> library(zoo)                                                                  
> zobj <- zoo(dat[,-1],dat[,1])                                                 
> plot(zobj,col=rainbow(ncol(zobj))) 

R 开发人员/贡献者(在本例中为 Gabor 和 Hadley)为我们提供了许多很棒的选择.(并且不能忘记格子包的 Deepayan)

R developers/contributors (Gabor and Hadley in this case) have blessed us with many great choices. (and can't forget Deepayan for the lattice package)

这篇关于将时间序列数据从宽格式重塑为高格式(用于绘图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆