nonoatfriday
nonoatfriday

Reputation: 31

Separate one column into several in R data frame and then pivot

I have a dataframe in the following format with two columns.

Column one are names, and column 2 are descriptions indicate levels in the hierarchy. i.e school A and school B are at the same level, Class is one level lower than school, so their des is longer, and there’s one more @ after its school des1@123, or 1@124. Then student…..

name        des
School A    1@123
School B    1@124
Class A     1@123@230
Class B     1@123@231
Class C     1@124@232
Class D     1@124@233
Student 1   1@123@230@001
Student 2   1@123@231@002
Student 3   1@123@231@003
Student 4   1@124@232@004
Student 5   1@124@233@005

I want to rearrange the data into few columns like pivoting, according to their des. i.e. not sure if we have any relevant codes in R? Thanks.

School A    Class A   Student 1
School A    Class B   Student 2
School A    Class B   Student 3
School B    Class C   Student 4
School B    Class D   Student 5

Upvotes: 3

Views: 358

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20463

This should get you most of the way, the rest is just recoding or lookups

library(tidyr)
library(dplyr)

separate(df, des, into = c("School_1", "School_2", "Class"), 
         sep = "@", extra = "drop") %>%
  unite(School, School_1:School_2) %>%
  .[grepl("Student", .$name), ]

#         name School Class
# 7  Student 1  1_123   230
# 8  Student 2  1_123   231
# 9  Student 3  1_123   231
# 10 Student 4  1_124   232
# 11 Student 5  1_124   233
# 12 Student 5  1_124   233

Upvotes: 1

Related Questions