The Smart Chef

data.table Wide to Long

Here's an example of converting data from wide to long using the data.table package in R. In data.table, the function we will use is called "melt"

Wide to Long

  

# Load the data.table library
library(data.table)

# Create a wide format dataset
wide_df <- data.table(
  id = c(1, 2, 3),
  x1 = c(10, 20, 30),
  x2 = c(40, 50, 60),
  x3 = c(70, 80, 90)
)

# Convert to long format using data.table's melt function
long_df <- melt(wide_df, id.vars = "id", variable.name = "variable", value.name = "value")

# Show the long format dataset
print(long_df)


   id variable value
1:  1      x1    10
2:  2      x1    20
3:  3      x1    30
4:  1      x2    40
5:  2      x2    50
6:  3      x2    60
7:  1      x3    70
8:  2      x3    80
9:  3      x3    90