需要逐行重新组织数据以对每一行执行计算

时间:2012-10-12 15:50:45

标签: r

我原来的数据框是这样的: X

Team  Date   variable  value
A 2012-07-01 Score      13
A 2012-07-02 Score      12
A 2012-07-03 Score      2097
A 2012-07-04 Score      45
A 2012-07-05 Score      41
A 2012-07-06 Score      763

需要像这样

z
    Team 2012-07-01 2012-07-02 2012-07-03 2012-07-04 2012-07-05 2012-07-06 
    A     13         12          2097      45        41         763

library(reshape)
z<-cast(x, Team + variable ~ Date)

我收到一条警告信息:

  

聚合需要fun.aggregate:length用作默认值

2 个答案:

答案 0 :(得分:1)

使用reshape2包中的dcast,它会正常工作!

x <- read.table(text='Team  Date   variable  value
A 2012-07-01 Score      13
A 2012-07-02 Score      12
A 2012-07-03 Score      2097
A 2012-07-04 Score      45
A 2012-07-05 Score      41
A 2012-07-06 Score      763', header=T)

library(reshape2)
dcast(x, Team + variable ~ Date)
 Team variable 2012-07-01 2012-07-02 2012-07-03 2012-07-04 2012-07-05 2012-07-06
1    A    Score         13         12       2097         45         41        763

编辑:

您可以使用统计信息中的reshape功能。如上所述,不需要额外的包裹。

Y <- reshape(x, v.names='value', idvar='Team', timevar='Date',direction='wide')
names(Y) <- sub('value.', '', names(Y))
Y
  Team variable 2012-07-01 2012-07-02 2012-07-03 2012-07-04 2012-07-05 2012-07-06
1    A    Score         13         12       2097         45         41        763

答案 1 :(得分:0)

无需特殊包装:

xtabs(value ~ Team + Date, x)
#     Date
# Team 2012-07-01 2012-07-02 2012-07-03 2012-07-04 2012-07-05 2012-07-06
#    A         13         12       2097         45         41        763
as.data.frame.matrix(xtabs(value ~ Team + Date, x))
#   2012-07-01 2012-07-02 2012-07-03 2012-07-04 2012-07-05 2012-07-06
# A         13         12       2097         45         41        763