Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Long to wide format using variable names

I have a wide dataset that looks like this:

dataset <- data.frame(id = c(1, 2, 3, 4, 5),
                      basketball.time1 = c(2, 5, 4, 3, 3),
                      basketball.time2 = c(3, 4, 5, 3, 2),
                      basketball.time3 = c(1, 8, 4, 3, 1),
                      volleyball.time1 = c(2, 3, 4, 0, 1),
                      volleyball.time2 = c(3, 4, 3, 1, 3),
                      volleyball.time3 = c(1, 8, 12, 2, 3))

What I want is the dataset in long format, with id, time, basketball, and volleyball as separate variables. I want to create the time column with three factors (time1, time2, and time3) using the string that is separated by "." at the end of the basketball and volleyball columns.

Thanks so much!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: fixed typo

>Solution :

We can usepivor_longer %>% pivot_wider. separateis not needed if we set the appropriate parameters to pivor_longer.

library(tidyr)

dataset %>%
        pivot_longer(cols = matches('time\\d+$'), names_to = c('sport', 'time'), names_pattern = '(.*)\\.(.*)') %>%
        pivot_wider(names_from = sport, values_from = value)

# A tibble: 15 × 5
      id time  basketball volleyball vollyeball
   <dbl> <chr>      <dbl>      <dbl>      <dbl>
 1     1 time1          2          2         NA
 2     1 time2          3          3         NA
 3     1 time3          1         NA          1
 4     2 time1          5          3         NA
 5     2 time2          4          4         NA
 6     2 time3          8         NA          8
 7     3 time1          4          4         NA
 8     3 time2          5          3         NA
 9     3 time3          4         NA         12
10     4 time1          3          0         NA
11     4 time2          3          1         NA
12     4 time3          3         NA          2
13     5 time1          3          1         NA
14     5 time2          2          3         NA
15     5 time3          1         NA          3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading