R - 合并一行中相同元素的信息

R - merge information of the same elements in one row

假设我有以下 data.frame。学生最多尝试 3 次测验。

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

现在我希望 data.frame 看起来像那样

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

每个学生只有一行,列中有不同的点和时间。 我怎样才能做到这一点?

这给出了所需的输出:

 df %>% 
  group_by(student) %>% 
  mutate(head = letters[row_number()]) %>%
  pivot_wider(id_cols = student, names_from = head, names_sep = "-", values_from = c(points, time)) %>% 
  pivot_longer(-student) %>% 
  arrange(str_sub(name, -1)) %>% 
  pivot_wider(student)

group_by()mutate() 提供必要的列标题,然后 pivot_wider() 完成工作。

最后三行给出了正确的顺序,尽管直接执行此操作可能是更好的方法。

使用 reshape

的基础 R 选项
reshape(
    transform(
        df,
        q = ave(id, id, FUN = seq_along)
    ),
    idvar = "id",
    timevar = "q",
    direction = "wide"
)

给予

  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