2

I want to delete columns based on certain conditions.

library(data.table)
dt <- data.table(1:4, rep(TRUE, 4), c(TRUE, FALSE, TRUE, TRUE))

In this case I want to delete columns that are all TRUE. Output should be

 # V1    V3
 #  1  TRUE
 #  2 FALSE
 #  3  TRUE
 #  4  TRUE

2 Answers 2

3

Filter() is a useful function for selecting columns of a data-frame according to whether a particular function evaluates to TRUE. In your case:

Filter(function(x) !all(x == TRUE), dt)

   V1    V3
1:  1  TRUE
2:  2 FALSE
3:  3  TRUE
4:  4  TRUE
Sign up to request clarification or add additional context in comments.

Comments

2

You can exclude them from selection using subsetting

dt[,!sapply(dt, function(x) all(x==TRUE)), with=FALSE]

Here the sapply(dt, function(x) all(x==TRUE)) part finds the columns where all values are TRUE. Then we negate it and use with=FALSE (since this is a data.table and not a data.frame)

On current devel version of data.table (2020-04-24), we can do this in .SDcols:

dt[ , .SD, .SDcols = function(x) !is.logical(x) || !all(x)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.