I'd like to melt a data.table without including any ID columns.
dt <- data.table::data.table(iris)[1:10]
data.table::melt(dt, measure.vars=c('Petal.Length', 'Petal.Width'))
Without specifying id.vars, all of the non measure.vars columns are treated as id.vars. This can be dealt with after the fact by only selecting variable/value from the melt.
For example, the below code produces the output I'm looking for:
data.table::melt(dt, measure.vars=c('Petal.Length', 'Petal.Width'))[,.(variable, value)]
But I would have thought it should be possible within the melt call itself? I've tried the below with no success.
data.table::melt(dt, measure.vars=c('Petal.Length', 'Petal.Width'), id.vars=NULL)
data.table::melt(dt, measure.vars=c('Petal.Length', 'Petal.Width'), id.vars=c())
data.table::melt(dt, measure.vars=c('Petal.Length', 'Petal.Width'), id.vars=list())
From the documentation:
If id.vars and measure.vars are both missing, all non-numeric/integer/logical columns are assigned as id variables and the rest as measure variables. If only one of id.vars or measure.vars is supplied, the rest of the columns will be assigned to the other. Both id.vars and measure.vars can have the same column more than once and the same column can be both as id and measure variables.
melt.data.table also accepts list columns for both id and measure variables.
c()
and NULL
are identical (e.g. identical(c(), NULL) == TRUE
), and NULL
is the value assigned internally to id.vars
when it is missing.
However, an empty integer or character vector will do the trick:
data.table::melt(dt, measure.vars=c('Petal.Length', 'Petal.Width'), id.vars=integer())
data.table::melt(dt, measure.vars=c('Petal.Length', 'Petal.Width'), id.vars=character())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With