Convert to long table generating subvariables within a variable with tidyr

Does this work:

library(dplyr)
library(tidyr)
df %>% pivot_longer(cols = !A, names_to = 'Number', values_to = 'Value') %>% type.convert(as.is = T) %>% 
    mutate(Variable = case_when(Number %in% c(1,2) ~ 'WW', Number  == 34 ~ 'MM', TRUE ~ 'EE')) %>% 
   select('Letter' = A, Number, Variable, Value)

Output:

# A tibble: 15 x 4
   Letter Number Variable Value
   <chr>   <int> <chr>    <dbl>
 1 A           1 WW         1.9
 2 A           2 WW         1.9
 3 A          34 MM         3.9
 4 A         158 EE         2.9
 5 A         190 EE        22.1
 6 B           1 WW         6.8
 7 B           2 WW         6.8
 8 B          34 MM         0.3
 9 B         158 EE         3  
10 B         190 EE         7.4
11 C           1 WW         4.7
12 C           2 WW         4.7
13 C          34 MM         2.7
14 C         158 EE        45  
15 C         190 EE        56  
> 

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top