r - 在 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 行数据),如果这会产生影响,则需要以这种方式进行转置。
解决方案
在使用 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)
推荐阅读
- java - 我应该使用什么命令从使用 Windows 注册表的上下文菜单中启动 jar 文件?
- c++ - 如何从仅使用空格作为分隔符的文件中获取要写入的二维数组
- javascript - Framework7 和 Material Design:样式未渲染
- r - 如何在 R 中的 ggplot 美学中使用先验中位数?
- c# - 在具有多个选项卡的 asp.net core razor 页面中按需加载 ViewComponent 数据
- c# - 嵌套 DTO - 发送回客户端时出错
- java - 如何使用 Picasso/Glide 从服务器加载更新的图像?
- angular - Angular 5:调用受 2 路 ssl 保护的 api
- r - 如何将行添加到单行中?
- python - keras输入问题中的密集网络