I want to subset a data.frame
based on if some variables are all positive, all negative or some combination in between. For n
variables this should lead to 2^n
possible combinations.
I think combn
can be used to achieve this but I'm struggling to do it properly.
Sample data:
library(data.table)
dt <- data.table(x = runif(100, -1, 1), y = runif(100, -1, 1), z = runif(100, -1, 1))
What I want:
dt[x < 0 & y < 0 z < 0, ]
dt[x < 0 & y < 0 z > 0, ]
dt[x < 0 & y > 0 z < 0, ]
dt[x < 0 & y > 0 z > 0, ]
dt[x > 0 & y < 0 z < 0, ]
dt[x > 0 & y < 0 z > 0, ]
dt[x > 0 & y > 0 z < 0, ]
dt[x > 0 & y > 0 z > 0, ]
What I've tried so far:
combinator <- function(z){
cnames <- colnames(z)
combinations <- t(combn(c(rep("<", ncol(z)), rep(">", ncol(z))),ncol(z)))
retval <- t(sapply(1:nrow(combinations), function(p){
sapply(1:ncol(z), function(q) paste(cnames[q], combinations[p,q], 0))
}))
return(apply(retval, 1, paste, collapse = " & "))
}
Output:
> l <- combinator(dt)
> l
[1] "x < 0 & y < 0 & z < 0" "x < 0 & y < 0 & z > 0" "x < 0 & y < 0 & z > 0" "x < 0 & y < 0 & z > 0"
[5] "x < 0 & y < 0 & z > 0" "x < 0 & y < 0 & z > 0" "x < 0 & y < 0 & z > 0" "x < 0 & y > 0 & z > 0"
[9] "x < 0 & y > 0 & z > 0" "x < 0 & y > 0 & z > 0" "x < 0 & y < 0 & z > 0" "x < 0 & y < 0 & z > 0"
[13] "x < 0 & y < 0 & z > 0" "x < 0 & y > 0 & z > 0" "x < 0 & y > 0 & z > 0" "x < 0 & y > 0 & z > 0"
[17] "x < 0 & y > 0 & z > 0" "x < 0 & y > 0 & z > 0" "x < 0 & y > 0 & z > 0" "x > 0 & y > 0 & z > 0"
> l[1]
[1] "x < 0 & y < 0 & z < 0"
> subset(dt, eval(l[1]))
Error in subset.data.table(dt, eval(l[1])) :
'subset' must evaluate to logical
Also if the following shows that I'm not listing all the desired combinations:
> unique(l)
[1] "x < 0 & y < 0 & z < 0" "x < 0 & y < 0 & z > 0"
[3] "x < 0 & y > 0 & z > 0" "x > 0 & y > 0 & z > 0"
the output should have 8 unique results instead of the 4 shown above.