如何使用重塑包重塑r中的数据

爸爸弗里德曼

我有看起来像这样的数据:

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
阿克伦

你可以试试

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))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章