user2354885
user2354885

Reputation:

Melt data for one column

I have this data:

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

And I want to make this output:

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

I tried to melt the data but it didn't work. Any suggestions?

Upvotes: 1

Views: 1390

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

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

Upvotes: 4

Related Questions