2

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.

Martin Gal
  • 16,640
  • 5
  • 21
  • 39

1 Answers1

3

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))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you very much, Ronak. Your advice perfectly worked for me! Seems like I need to get familiar with how to use "name_patterns" (especially regular expressions) and ".value". I will look for the info about them myself. – Shunsuke NISHIOKA May 03 '20 at 13:25
  • Could you explain '\\d+'? – Masoud Sep 16 '21 at 19:12
  • @Masoud Read the help page: ?regex. It's a pattern to match tow capture classes: 1) to be any non-digit followed by 2) one or more digits in together. – IRTFM Nov 04 '21 at 04:30
  • @IRTFM, I studied it. First term capture any character until a digit with length>= 1 that capture by second term! Thanks, I think I understand it now! – Masoud Nov 04 '21 at 13:22