0

I have a df looks like below.

     Year Month Cont

1     2011     Apr 1376

2     2012     Apr 1232

3     2013     Apr 1360

4     2014     Apr 1294

5     2015     Apr 1344

6     2011     Aug 1933

7     2012     Aug 1930

8     2013     Aug 1821

9     2014     Aug 1845

10    2015     Aug 1855

So my question is how can I switch the rows in "Month" the column. The result should look like this.

    Cont  Apr  Aug
1   2011    1376    1933

2   2012    1232    1930

3   2013    1360    1821

4   2014    1294    1845

5   2015    1344    1855
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Alan
  • 11
  • 2

2 Answers2

1

You can use reshape2:

library(reshape2)
dcast(df, Year~Month, value.var="Cont")

Or tidyr:

library(tidyr)
spread(df, Month, Cont)
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
0

Please refer the following code

> dat <- read.table("data.txt", quote="\"", comment.char="")
> dat
     V1  V2   V3
1  2011 Apr 1376
2  2012 Apr 1232
3  2013 Apr 1360
4  2014 Apr 1294
5  2015 Apr 1344
6  2011 Aug 1933
7  2012 Aug 1930
8  2013 Aug 1821
9  2014 Aug 1845
10 2015 Aug 1855
> library(reshape2)
> dcast(dat, V1~V2)
Using V3 as value column: use value.var to override.
    V1  Apr  Aug
1 2011 1376 1933
2 2012 1232 1930
3 2013 1360 1821
4 2014 1294 1845
5 2015 1344 1855
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
sairaamv
  • 86
  • 4