在r中将数据帧从long转换为宽,但需要进行日期转换

时间:2015-03-01 04:17:07

标签: r long-integer reshape

我有一个这样的数据框(每个“NUMBER”表示一个学生):

NUMBER  Gender  Grade Date.Tested   WI  WR  WZ
1       F       4     2014-02-18    6   9   10
1       F       3     2014-05-30    9   8   2
2       M       5     2013-05-02    7   9   15
2       M       4     2009-05-21    5   7   2
2       M       5     2010-04-29    9   1   4

我知道我可以使用:

cook <- reshape(data, timevar= "?", idvar= c("NUMBER","Gender"), direction = "wide")

将其更改为宽幅格式。但是,我想将date.tested删除到时间(第1次,第2次......等),并指出等级。

我最终想要的是这样的:

NUMBER  Gender Grade1 Grade 2 Grade 3 WI1  WR1  WZ1  WI2  WR2  WZ2 WI3  WR3  WZ3
1       F       3      4       NA     9    8     2   6      9   10   NA   NA   NA

其余的“NUMBER”。

我搜索了很多但没有找到答案。有人可以帮我吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

尝试

 data$id <- with(data, ave(seq_along(NUMBER), NUMBER, FUN=seq_along))
 reshape(data, idvar=c('NUMBER', 'Gender'), timevar='id', direction='wide')

如果您希望Date.Tested变量包含在&#39; idvar&#39;并且您只需要该组的第一个值(&#39; NUMBER&#39;或者#39; GENDER&#39;)

 data$Date.Tested <- with(data, ave(Date.Tested, NUMBER,
                           FUN=function(x) head(x,1)))
 reshape(data, idvar=c('NUMBER', 'Gender', 'Date.Tested'), 
                timevar='id', direction='wide')