首页 > 解决方案 > 在 R 中传播数据

问题描述

我正在尝试在 R 数据框中传播单列。我已经查看了许多关于 SO 的帖子,但无法让我的解决方案发挥作用,因为大多数解决方案似乎都需要一个公式(计数、平均值、总和等)。我只是想传播一列字符。例如:

library(tidyverse)

school<- c("univ1", "univ2","univ1", "univ2","univ1" )
student<-c('bob', 'sally','ben','trudy','evan')

df <- data.frame(school, student)

产生:

school            student
univ1             bob
univ2             sally
univ1             ben
univ2             trudy
univ1             evan

但我想要输出的是:

school            student1      student2     student2
univ1             bob           ben          evan
univ2             sally         trudy

我将如何做到这一点?我尝试了 spread() 和 pivot_wider() 但都不起作用。有什么想法吗?实际数据集非常大(超过 300k 行数据),如果这会产生影响,则需要以这种方式进行转置。

标签: rtidyverse

解决方案


在使用 spread() 之前,您需要指定 student1、student2 和 student3。我建议添加一个新列来传播,例如:

df %>%
group_by(school) %>%
mutate(
 student_number = row_number(),
 student_number = str_c("student_", student_number)
) %>%
ungroup() %>%
spread(student_number,student)

推荐阅读