如何使用reshape包重新整形r中的数据

时间:2014-12-05 15:43:29

标签: r reshape

我的数据看起来像这样:

Id    date         result
1     12/2/1997    1
1     04/5/2000    0
2     06/4/1998    1
2     18/6/1999    1
2     20/3/2000    0

我希望它看起来像:

Id date.1    result.1 date.2     result.2 date.3    result.3
1  12/2/1997 1        04/5/2000  0        na        na
2  06/4/1998 1        18/6/1999  1        20/3/2000 0

1 个答案:

答案 0 :(得分:3)

你可以尝试

df$indx <- with(df, ave(seq_along(Id), Id, FUN=seq_along))
df1 <- reshape(df, idvar='Id', timevar='indx', direction='wide')
df1
#   Id    date.1 result.1    date.2 result.2    date.3 result.3
#1  1 12/2/1997        1 04/5/2000        0      <NA>       NA
#3  2 06/4/1998        1 18/6/1999        1 20/3/2000        0

更新

如果您想使用indx

添加新列
 df1$newCol <- tail(unique(df$indx), nrow(df1))
 df1
 #  Id    date.1 result.1    date.2 result.2    date.3 result.3 newCol
 #1  1 12/2/1997        1 04/5/2000        0      <NA>       NA      2
 #3  2 06/4/1998        1 18/6/1999        1 20/3/2000        0      3

数据

df <- structure(list(Id = c(1L, 1L, 2L, 2L, 2L), date = c("12/2/1997", 
"04/5/2000", "06/4/1998", "18/6/1999", "20/3/2000"), result = c(1L, 
0L, 1L, 1L, 0L)), .Names = c("Id", "date", "result"), class = "data.frame",
row.names = c(NA, -5L))