I am transposing a data.table and have chosen to use reshape2:::dcast
, however I am plagued by a strange handling of the data.table... here is a toy data set that replicates the behavior:
> library(data.table)
> library(reshape2)
> DT <- structure(list(STORE = c(32123L, 32469L, 33177L, 33484L, 34772L, 34875L),
VOLUME = c(343.87205, 599.78335, 1665.90895, 712.0343, 465.6489, 622.5189)),
.Names = c("STORE", "VOLUME"),
sorted = "STORE",
class = c("data.table", "data.frame"),
row.names = c(NA, -6L))
> (R1 <- dcast(DT, . ~ STORE, value.var = "VOLUME"))
. 32123 32469 33177 33484 34772 34875
1 . 343.8721 599.7834 1665.909 712.0343 465.6489 622.5189
Perfect, exactly what I want it to look like (dropping the .
column is no biggy) -- but it is no longer classed as a data.table:
> class(R1)
[1] "data.frame"
I attempted to explicitly call the method for data.tables in the data.table package, but R now does not like the formula:
> data.table:::dcast.data.table(DT, . ~ STORE, value.var = "VOLUME")
Error in data.table:::dcast.data.table(DT, . ~ STORE, value.var = "VOLUME") :
LHS of formula evaluates to 'character(0)', invalid formula.
2: stop("LHS of formula evaluates to 'character(0)', invalid formula.")
1: data.table:::dcast.data.table(DT, . ~ STORE, value.var = "VOLUME")
This can easily be worked around by creating a dummy pivot column to be dropped after the transposition:
> DT[, "dummy" := NA]
> (R2 <- data.table:::dcast.data.table(DT, dummy ~ STORE, value.var = "VOLUME"))
dummy 32123 32469 33177 33484 34772 34875
1: NA 343.8721 599.7834 1665.909 712.0343 465.6489 622.5189
> class(R2)
[1] "data.table" "data.frame"
However, the fact that data.table:::dcast.data.table
did not have handling for a NULL LHS of the cast formula leads me to believe I am going about this all wrong -- is there a "data.table" way to do this?
setDT(dcast(DT, . ~ ...))
– Negatrondcast.data.table(DT, .~STORE, value.var = "VOLUME")[,-1,with=FALSE]
– Kowtko