Melt data for one column

99封情书 提交于 2020-01-05 20:52:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!