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

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))

Leave a Comment