I have data that look like this:
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
And I want it to look like:
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
You can try
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
If you want to add a new column using the 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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.