1

I have the following table:

Table <- data.frame(ID=c(1,2),A=c("TRUE","FALSE"), B=c("1","2"))

ID A B
1 "TRUE" "1"
2 "FALSE" "2"

I want to transform it into the following table:

Table_transformed <- data.frame(ID=c(1,2,1,2),COLUMN=c("A","A","B","B"), VALUE=c("TRUE","FALSE","1","2"))

ID COLUMN VALUE
1 A "TRUE"
2 A "FALSE"
1 B "1"
2 B "2"

How to do this?

I have not found a way to do this yet without using non-generalized for-loops etc.

Eric
  • 11
  • 2

1 Answers1

0

A tidyverse solution:

df1 <- data.frame(ID=c(1,2),A=c("TRUE","FALSE"), B=c("1","2"))

library(tidyr)
library(dplyr)

df1 |> 
pivot_longer(-ID, names_to = "Column", values_to = "VALUE") |> 
arrange(Column)  

#> # A tibble: 4 × 3
#>      ID Column VALUE
#>   <dbl> <chr>  <chr>
#> 1     1 A      TRUE 
#> 2     2 A      FALSE
#> 3     1 B      1    
#> 4     2 B      2

Created on 2023-06-27 with reprex v2.0.2

Peter
  • 11,500
  • 5
  • 21
  • 31