问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/18429003/melt-data-for-one-column