How to distribute data using r

I have my data like this

windspeed      month
1.2             Jan
2               Feb
3.5             Mar
2.6             Apr
5.9             Jun
2.5             Jul

      

I want to receive data like this

Jan   Feb   Mar   Apr    Jun   Jul  
1.2    2     3.5    2.6   5.9   2.5  

      

+3


source to share


4 answers


just a base R (even if it setNames

belongs to a package stats

):

setNames(dat$windspeed, dat$month)
Jan Feb Mar Apr Jun Jul 
1.2 2.0 3.5 2.6 5.9 2.5 

      



yes there is (are) way (s), here is one:

as.data.frame(t(setNames(dat$windspeed, dat$month)))
  Jan Feb Mar Apr Jun Jul
1 1.2   2 3.5 2.6 5.9 2.5

      

+4


source


What about



t(unstack(DF, windspeed ~ month))

    Apr Feb Jan Jul Jun Mar
res 2.6   2 1.2 2.5 5.9 3.5

      

+4


source


The R is very useful packages, suitable for operations such as reshape

, data.table

,tidyr

library(reshape2)
library(data.table)

dcast.data.table(melt(setDT(data), id.vars = "month"), variable ~ month)
#   variable Apr Feb Jan Jul Jun Mar
#1: windspeed 2.6   2 1.2 2.5 5.9 3.5

library(reshape2)
library(tidyr)
spread(melt(data), month, value)

#   variable Apr Feb Jan Jul Jun Mar
#1 windspeed 2.6   2 1.2 2.5 5.9 3.5

      

+2


source


You can try this:

DF <- data.frame(windspeed=c(1.2, 2, 3.5, 2.6, 5.9, 2.5), month=c('Jan', 'Feb', 'Mar', 'Apr', 'Jun', 'Jul'))
DF <- t(DF)
colnames(DF) = DF[2, ]
DF <- DF[1,]
DF

      

Gives you

 Jan   Feb   Mar   Apr   Jun   Jul 
"1.2" "2.0" "3.5" "2.6" "5.9" "2.5"

      

0


source







All Articles