Subset rows in data.table if all specified columns match a criterion
You can apply
row-wise and then check if all
the values in that row is greater than 0.
a[apply(a[, cols, with = FALSE], 1, function(x) all(x>0))]
# n x y z
#1: case2 2 1 1
We can use Reduce
with .SDcols
. Specify the columns of interest in .SDcols
, loop through the Subset of Data.table (.SD
) check whether it is equal 0, get the sum of each row with Reduce
, negate (!
) to get a logical vector which returns TRUE when there are no 0 elements and use that to subset the rows of 'a'
a[a[, !Reduce(`+`, lapply(.SD, `<=`, 0)),.SDcols = cols]]
# n x y z
#1: case2 2 1 1
Or as @Frank mentioned in the comments, pmin
can be used as well
a[a[, do.call(pmin, .SD), .SDcols = cols]>0]
You can try
a[rowSums(a[, lapply(.SD, `<=`, 0), .SDcols=cols])==0]
# n x y z
#1: case2 2 1 1
It selects the rows for which there are no cols
columns with a value below or equal to zero (you can also use condition x>0 and check for ==length(cols)
if you prefer).