Julien Sawadogo
Julien Sawadogo

Reputation: 55

How to reshape dataset

I have 2 colomns, the first one is the months and the second one is the value like that

month         windspeed
jan            2.5
jan            1.6
jan            4.5
feb            3.6
feb            3.5
feb            1.8
mar            4.2
mar            4.6
mar            3.8

I want to reshape that way

jan    feb    mar
2.5    3.6    4.2
1.6    3.5    4.6
4.5    1.8    3.8

Need help!

Upvotes: 0

Views: 60

Answers (1)

akrun
akrun

Reputation: 887831

You can use unstack from base R

 unstack(df1, windspeed~month)
 #  jan feb mar
 #1 2.5 3.6 4.2
 #2 1.6 3.5 4.6
 #3 4.5 1.8 3.8

Or create a sequence column grouped by 'month' and then use dcast

 library(reshape2)
 df2 <- transform(df1, indx=ave(seq_along(month), month, FUN=seq_along))
 dcast(df2, indx~month, value.var='windspeed')[-1]
 #  jan feb mar
 #1 2.5 3.6 4.2
 #2 1.6 3.5 4.6
 #3 4.5 1.8 3.8

Upvotes: 3

Related Questions