Rearrangement of columns in a dataframe

Hi. I have a dataset of students with the details of teachers (like their education and experience). The raw data is like the one I show below in data1. The data of teachers lie in different columns. I want the data in the desired format as shown in the data2.
How can I do this?

  ~student_id, ~tch1_degree, ~tch1_exp, ~tch2_degree, ~tch2_exp, ~tch3_degree, ~tch3_exp,
       "S001",           1L,       14L,           NA,        NA,           NA,        NA,
       "S002",           NA,        NA,           2L,       22L,           NA,        NA,
       "S003",           NA,        NA,           NA,        NA,           3L,       16L,
       "S004",           NA,        NA,           NA,        NA,           2L,       14L,
       "S005",           NA,        NA,           2L,       24L,           NA,        NA,
       "S006",           NA,        NA,           1L,       22L,           NA,        NA,
       "S007",           NA,        NA,           1L,       20L,           NA,        NA,
       "S008",           2L,       10L,           NA,        NA,           NA,        NA,
       "S009",           2L,       10L,           NA,        NA,           NA,        NA

         ~student_id, ~tch_degree, ~tch_exp,
              "S001",          1L,      14L,
              "S002",          2L,      22L,
              "S003",          3L,      16L,
              "S004",          2L,      14L,
              "S005",          2L,      24L,
              "S006",          1L,      22L,
              "S007",          1L,      20L,
              "S008",          2L,      10L,
              "S009",          2L,      10L

You can do something like this:

(degs <- select(data1,
                ends_with("degree")) %>% names())
(exp <- select(data1,
                ends_with("exp")) %>% names())

          tch_degree = coalesce(!!!syms(degs)),
          tch_exp = coalesce(!!!syms(exp)))

This is working for me. Thanks a lot. But just an add-on question, why is a bracket put before "degs" and "exp"?
I didn't get that. The code was working without that as well.

It causes a print to console

oh I see. Thank you.

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.