Spread Data in R [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-12 20:33:54

问题


I am trying to spread a single column in an R dataframe. I have reviewed many posts on SO, but cant get my solution to work because most solutions seem to require a formula (count, mean, sum, etc). I am simply looking to spread a column of characters. For example:

library(tidyverse)

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

df <- data.frame(school, student)

produces:

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

but what I am trying to output is:

school            student1      student2     student2
univ1             bob           ben          evan
univ2             sally         trudy

How would I accomplish this? I tried spread() and pivot_wider() but neither work. Any thoughts? The actual dataset is quite large (over 300k rows of data) that will need transposed in this manner if that makes a difference.


回答1:


For each group you specify the student number and spread according to that

df %>% group_by(school) %>% mutate(n=paste("student",1:n())) %>% spread(n,student)



回答2:


You need to specify the student1, student2 and student3 before you use spread(). I'd suggest adding a new column to spread by, for example:

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


来源:https://stackoverflow.com/questions/58647667/spread-data-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!