I've got a data matrix where each row represents a course and in another column a teacher is assigned:
I would like to transform the data to this form:
But what I get is this form:
This is my code so far:
course <- c('Math1', 'English', 'Biology', 'Math2', 'Physics')
teacher <- c('Teacher1', 'Teacher1', 'Teacher1', 'Teacher2', 'Teacher2')
data <- data.frame(course, teacher)
data <- tibble::rowid_to_column(data, "courseID")
data_wide <- data %>%
pivot_wider(values_from = course, names_from = courseID)
So the problem is, that for each course, a new variable is created. While for teacher2 the course Math2 should be on column course1 (since it’s his first course), with my code it gets course4 and filling up the preceding columns with NAs.
Edit: my question was closed because it was considered a duplicate of How to reshape data from long to wide format but this is not the focus of my question: I already succeeded to transform to wide format, but for example for teacher2 Math2 is his first course, so it should appear in column course1 instead of creating a new column course4.