R-data table - express multiple succintly subset conditions

I have a data table that looks like this:

set.seed(1)
n <- 10; p <- 6
dat <- as.data.table(matrix(sample(c(0,1),n*p,replace = TRUE), n, p) )
setnames(dat, letters[1:p])

I want to subset the data table to contain only the rows with the columns d, e, fmore than 0. I can do this with the following code:

dat[d > 0 & e > 0 & f > 0]

However, when I try to express the same subset condition as follows, this gives me an error:

cols <- c("d", "e", "f")
dat[cols > 0]

What is the right way to do this?

Thank.

+4
source share
1 answer

"cols", .SDcols, data.table(.SD), , 0, Reduce &, , , , 0 ,

dat[dat[, Reduce(`&`, lapply(.SD, `>`, 0)),.SDcols = cols]]
+3

Source: https://habr.com/ru/post/1675184/


All Articles