Pivot longer with multiple variables

I have data of teachers in different schools given in a horizontal format. I need to change that into the desired output as in data frame "data2". How can I do it using pivot_longer?


  ~school_code,      ~school_name, ~tch_code1, ~tch_name1, ~tch_code2, ~tch_name2, ~tch_code3, ~tch_name3, ~num_class, ~strength,
        "S001",      "GHPS HUBLI",     "S1T1",   "Nithin",     "S1T2",    "Nehru",     "S1T3",    "Zidan",         1L,       21L,
        "S002",      "GHPS UNKAL",     "S2T1",     "Raja",     "S2T2",    "Gandi",         NA,         NA,         2L,       41L,
        "S003",   "GLPS RAJNAGAR",     "S3T1",    "Himan",     "S3T2",     "Zayn",         NA,         NA,         1L,       45L,
        "S004",   "GHPS CR NAGAR",     "S4T1",    "Nayan",         NA,         NA,     "S4T3",     "Find",         1L,       12L,
        "S005", "GLPS VIDYANAGAR",     "S5T1",    "Budan",         NA,         NA,     "S5T3",   "Vilder",         2L,       55L

#desired output
  ~school_code,      ~school_name, ~tch_code, ~tch_name, ~numclass, ~strength,
        "S001",      "GHPS HUBLI",    "S1T1",  "Nithin",        1L,       21L,
        "S001",      "GHPS HUBLI",    "S1T2",   "Nehru",        1L,       21L,
        "S001",      "GHPS HUBLI",    "S1T3",   "Zidan",        1L,       21L,
        "S002",      "GHPS UNKAL",    "S2T1",    "Raja",        2L,       41L,
        "S002",      "GHPS UNKAL",    "S2T2",   "Gandi",        2L,       41L,
        "S003",   "GLPS RAJNAGAR",    "S3T1",   "Himan",        1L,       45L,
        "S003",   "GLPS RAJNAGAR",    "S3T2",    "Zayn",        1L,       45L,
        "S004",   "GHPS CR NAGAR",    "S4T1",   "Nayan",        1L,       12L,
        "S004",   "GHPS CR NAGAR",    "S4T3",    "Find",        1L,       12L,
        "S005", "GLPS VIDYANAGAR",    "S5T1",   "Budan",        2L,       55L,
        "S005", "GLPS VIDYANAGAR",    "S5T3",  "Vilder",        2L,       55L
Created on 2022-06-27 by the reprex package (v2.0.1)
data %>% 
  pivot_longer(starts_with("tch")) %>% 
  mutate(name = str_remove(name, "[0-9]")) %>% 
  pivot_wider(names_from = name, values_from = value, values_fn = list) %>% 
  unnest(c(tch_code, tch_name)) %>% 
  drop_na() %>% 
  relocate(where(is.numeric), .after = last_col())

Thank you for this.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.