Reputation: 867
Is there anyway to incorporate conditions/restrictions into expand.grid
in R?
As an example, how would I prevent the combination c(1,1,1)
and c(2,2,2)
from appearing while the grid is being created? Is there a scalable solution that would work with many restrictions? My grid is large and my memory cannot handle it, e.g Error: cannot allocate vector of size 32.0 Gb
, so subsetting after the grid is created is not an option.
expand.grid(A = rep(1:2),
B = rep(1:3),
C = rep(1:4))
Code below does not work:
expand.grid(A[!((A==1 & B==1 & C==1) & (A==2 & B==2 & C==2))] = rep(1:2),
B[!((A==1 & B==1 & C==1) & (A==2 & B==2 & C==2))] = rep(1:3),
C[!((A==1 & B==1 & C==1) & (A==2 & B==2 & C==2))] = rep(1:4))
as.data.frame(expand.grid(A = rep(1:2),
B = rep(1:3),
C = rep(1:4)))[!((A==1 & B==1 & C==1) & (A==2 & B==2 & C==2))]
Thanks!
Upvotes: 3
Views: 804
Reputation: 107767
Simply assign the expand.grid
data frame and then run needed logic which you can shorten by comparing equality across all columns (A==C
not needed per the transitive property of equality):
d1 <- expand.grid(A = rep(1:2),
B = rep(1:3),
C = rep(1:4))
d1 <- with(d1, d1[!(A==B & B==C),])
Upvotes: 1
Reputation: 887901
If we create the dataset
d1 <- expand.grid(A = rep(1:2),
B = rep(1:3),
C = rep(1:4))
Can use rowSums
to check if the data is equal to the first column
d1[!!rowSums(d1 != d1[,1]),]
Upvotes: 1