0

Consider the following data in a long format:

dt <- data.table(name = rep(c('A1','A2','A3'),3), value = rnorm(9))

I'm looking to transform dt to a wide format table, where name would correspond to column names, and value would correspond to the column values. I do not have the id column to assign, but we can assume that the entries in dt are ordered (i.e., the first row should contain the first 3 vertical entries in my example).

I'm looking for something similar to tidyr:::pivot_wider(dt, names_from = 'name', values_from = 'value'), but would prefer if the solution would not use any tidyverse package and stick to data.frame (or, preferably, data.table).

Are there any straightforward solutions already existing, or will I need to generate the ID's and use dcast? In other words, do we have anything simpler (or alternative) than the following:

ncol <- length(unique(dt$name))
dt$ID <- rep(1:ncol, each = nrow(dt)/ncol)
dcast(dt, ID ~ name, value.var = 'value')
runr
  • 1,142
  • 1
  • 9
  • 25

0 Answers0