Skip to content

Subsetting columns based on a condition can lead to errors #1477

@MichaelChirico

Description

@MichaelChirico

Consider:

DT <- data.table(a = 0L:1L, b = c(1L, 1L))
DT[ , lapply(.SD, function(x) if (all(x)) x)]

Which gives error:

Error in setnames(jval, jvnames) :
Can't assign 2 names to a 1 column data.table

That is, j evaluates to a single column (b) but jvnames still contains both columns a and b.

Does this happen for a particular reason? The above seems like the most natural way to subset columns to me.

My current workaround looks atrocious:

DT[ , mget(names(.SD)[sapply(.SD, function(x) all(x == 1))])]

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions