如何用r传播数据

时间:2015-07-11 20:09:41

标签: r dataframe reshape

我有我的数据

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

我想获得这种数据

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

4 个答案:

答案 0 :(得分:4)

只是基数R(即使setNames实际上属于stats包):

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

是的,有一种方式,这里是一种方式:

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

答案 1 :(得分:4)

怎么样?
t(unstack(DF, windspeed ~ month))

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

答案 2 :(得分:2)

R中也有一些非常有用的包,适用于reshapedata.tabletidyr

等操作
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

答案 3 :(得分:0)

你可以试试这个:

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

给你

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