0

I have a dataframe df1 like this:

A    B    C
d    1    4
d    3    5 
e    2    6
e    1    4

I like to move the column names + values of B and C into rows under new columns R1 & R2:

A    R1   R2
d    B    1
d    C    4
d    B    3 
d    C    5
e    B    2
e    C    6
e    B    1
e    C    4

Thanks in advance

Rhulsb
  • 303
  • 2
  • 5

1 Answers1

1

Using tidyr::pivot_longer this could be achieved like so:

d <- read.table(text = "A    B    C
d    1    4
d    3    5 
e    2    6
e    1    4", header = TRUE)
d
#>   A B C
#> 1 d 1 4
#> 2 d 3 5
#> 3 e 2 6
#> 4 e 1 4
tidyr::pivot_longer(d, -A, names_to = "R1", values_to = "R2")
#> # A tibble: 8 x 3
#>   A     R1       R2
#>   <chr> <chr> <int>
#> 1 d     B         1
#> 2 d     C         4
#> 3 d     B         3
#> 4 d     C         5
#> 5 e     B         2
#> 6 e     C         6
#> 7 e     B         1
#> 8 e     C         4
stefan
  • 90,330
  • 6
  • 25
  • 51