0

Is there a way to transform the data. Example

asd <- data.frame(a = c(1,2,3), b = c(6,7,8), met1 = c("A","A","A"), def1 = c("z", "x", "y"),met2 = c("A1","A1","A1"), def2 = c("z1", "x1", "y1") )
asd
  a b met1 def1 met2 def2
1 1 6    A    z   A1   z1
2 2 7    A    x   A1   x1
3 3 8    A    y   A1   y1

Expected output

new_asd 
  a b   met   def 
1 1 6    A    z   
2 2 7    A    x   
3 3 8    A    y   
4 1 6    A1   z1   
5 2 7    A1   x1  
6 3 8    A1   y1

So basically at met values should be in 1 column and similarly for def

manu p
  • 952
  • 4
  • 10

1 Answers1

0

A possible solution:

library(tidyverse)

asd <- data.frame(a = c(1,2,3), b = c(6,7,8), met1 = c("A","A","A"), def1 = c("z", "x", "y"),met2 = c("A1","A1","A1"), def2 = c("z1", "x1", "y1") )

asd %>% 
  pivot_longer(cols = c(-a, -b)) %>% 
  mutate(name = str_remove(name, "\\d+$")) %>% 
  pivot_wider(id_cols = c(a,b), values_fn = list) %>% 
  unnest(cols = c(met,def))

#> # A tibble: 6 × 4
#>       a     b met   def  
#>   <dbl> <dbl> <chr> <chr>
#> 1     1     6 A     z    
#> 2     1     6 A1    z1   
#> 3     2     7 A     x    
#> 4     2     7 A1    x1   
#> 5     3     8 A     y    
#> 6     3     8 A1    y1
PaulS
  • 21,159
  • 2
  • 9
  • 26