将多列堆叠成一列

时间:2015-03-02 17:32:11

标签: r

我有一个包含多列的数据,我想要堆叠它。我的数据看起来像

January February    March

20.5733 47.3457 47.8473
-9999   -9999   -9999
18.8403 41.3779 44.6814
23.0879 35.9153 41.216
43.49   31.85   40.17
-9999   -9999   -9999
-9999   -9999   -9999
15.1745 43.8709 46.5024

我需要以下数据

Janaury 20.5733
January -9999
January 18.8403
Janaury 23.0879
January 43.49
January -9999
Janaury -9999
January 15.1745
February    47.3457
February    -9999
February    41.3779
February    35.9153
February    31.85
February    -9999
February    -9999
February    43.8709
March   47.8473
March   -9999
March   44.6814
March   41.216
March   40.17
March   -9999
March   -9999
March   46.5024

由于 加文

1 个答案:

答案 0 :(得分:2)

完全来自您的问题标题,请查看stack,例如stack(mydf)

以下是前10行:

> head(stack(mydf), 10)
       values      ind
1     20.5733  January
2  -9999.0000  January
3     18.8403  January
4     23.0879  January
5     43.4900  January
6  -9999.0000  January
7  -9999.0000  January
8     15.1745  January
9     47.3457 February
10 -9999.0000 February

热门套餐包括“reshape2”和“tidyr”,其方法如下:

library(reshape2)
melt(mydf)

library(tidyr)
gather(mydf, var, val, January:March)