Search code examples
rdataframemergerow

R - merge information of the same elements in one row


Say I have the following data.frame. The students had up to 3 attempts at a quiz.

df <- data.frame(id = c(1, 1, 2, 3, 3, 3), points = c(3, 4, 5, 2, 6, 8), value = c(5, 5, 6, 8, 6, 2))
df

#>   student points time
#> 1       1      3    5
#> 2       1      4    5
#> 3       2      5    6
#> 4       3      2    8
#> 5       3      6    6
#> 6       3      8    2

Now I want the data.frame to look like that

#> id points-a time-a points-b time-b  points-c time-c
#>  1        3      5        4      5        NA     NA
#>  2        5      6       NA     NA        NA     NA
#>  3        2      8        6      6         8      2

Just one row for every student with the different points and times in columns. How can I achieve that?


Solution

  • A base R option using reshape

    reshape(
        transform(
            df,
            q = ave(id, id, FUN = seq_along)
        ),
        idvar = "id",
        timevar = "q",
        direction = "wide"
    )
    

    gives

      id points.1 value.1 points.2 value.2 points.3 value.3
    1  1        3       5        4       5       NA      NA
    3  2        5       6       NA      NA       NA      NA
    4  3        2       8        6       6        8       2