我的数据看起来像这样:
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
答案 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))