1

我有这个数据:

 datetime stock
 2010-01-01 4
 2010-01-02 7
 2010-01-03 2
 2010-01-04 9

我想做这个输出:

 datetime stock val
 2010-01-01 4    stock
 2010-01-02 7    stock
 2010-01-03 2    stock
 2010-01-04 9    stock

我试图融化数据,但没有奏效。有什么建议么?

4

1 回答 1

4

I don't know what you tried, but both of the following options work for me.

Assuming your data.frame is called "mydf":

Option 1: stack from Base R

cbind(mydf[1], stack(mydf[-1]))
#     datetime values   ind
# 1 2010-01-01      4 stock
# 2 2010-01-02      7 stock
# 3 2010-01-03      2 stock
# 4 2010-01-04      9 stock

Option 2: melt from "reshape2"

library(reshape2)
melt(mydf, id.vars="datetime")
#     datetime variable value
# 1 2010-01-01    stock     4
# 2 2010-01-02    stock     7
# 3 2010-01-03    stock     2
# 4 2010-01-04    stock     9
于 2013-08-25T12:33:19.997 回答