Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify an empty id.vars vector when melting a data.table?

Tags:

r

data.table

melt

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.

like image 687
logworthy Avatar asked Mar 03 '23 04:03

logworthy


1 Answers

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())
like image 123
logworthy Avatar answered Mar 08 '23 10:03

logworthy