Search code examples
rtidyversetidyrreshape2

How to use Pivot_longer to reshape from wide-type data to long-type data with multiple variables


I would like to ask how to reshape the following dataframe from wide-type to long-type. The wide-type data is as follows.

Wide-type data before reshaping:

enter image description here

The long type data, i.e. the dataframe that I would like to get, is as follows.

Long-type data after reshaping:

Long-type data after reshaping

Hugely appreciate if you could give me tips to do this using pivot-longer. I could reshape the data separately by BLS and ELS by writing:

df_long_BLS <- df %>%
pivot_longer(
cols = starts_with("BLS_tchrG"),
names_to = "grade",
names_prefix = "BLS_tchrG",
values_to = "BLS_tchrG"
)
df_long_ELS <- df %>%
pivot_longer(
cols = starts_with("ELS_tchrG"),
names_to = "grade",
names_prefix = "ELS_tchrG",
values_to = "ELS_tchrG"
)

But in this way I need to merge the 2 separate files. I would like to know how to do this data reshape without making 2 separate files.


Solution

  • You can try :

    tidyr::pivot_longer(df, cols = -ID_IE, 
                        names_to = c('.value', 'grade'), 
                        names_pattern = '(.*)(\\d+)')
    
    # A tibble: 8 x 4
    #  ID_IE grade BLS_tchrG ELS_tchrG
    #  <dbl> <chr>     <dbl>     <dbl>
    #1  2135 2             1         1
    #2  2135 7             1         1
    #3  2101 2             0         0
    #4  2101 7             2         0
    #5  2103 2             0         0
    #6  2103 7             3         0
    #7  2111 2             1         1
    #8  2111 7             4         1
    

    data

    Tried on this data :

    df <- data.frame(ID_IE = c(2135, 2101, 2103, 2111), BLS_tchrG2 = c(1, 0, 0, 1), 
                     BLS_tchrG7 = 1:4,
                     ELS_tchrG2 = c(1, 0, 0, 1), ELS_tchrG7 = c(1, 0, 0, 1))