The Smart Chef

data.table Long to Wide

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

Long to Wide

  

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

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

# Convert to wide format using data.table's dcast function
wide_df <- dcast(long_df, id ~ variable, value.var = "value")

# Show the wide format dataset
print(wide_df)

   id  x1  x2  x3
1:  1  10  40  70
2:  2  20  50  80
3:  3  30  60  90