Reputation: 199
Suppose I got a list (in my situation the number of elements in the list is variable),
tmp=c('X1','X2','X3','X4')
I'd like to pass each element to the expand grid function like this:
tmp1=expand.grid(X1=c(0,1),X2=c(0,1),X3=c(0,1),X4=c(0,1))
where each element can just take values 0 and 1. How could I achieve this?
Thanks.
Upvotes: 0
Views: 194
Reputation: 886938
We can use mget
to get the values of the elements in the 'tmp' vector
as a list
and then wrap it with expand.grid
.
expand.grid(mget(tmp))
Or if these are not objects, but the column names we need to create with expand.grid
, then place the vector c(0,1)
in a list
, replicate it by the length
of 'tmp', do the expand.grid
and set the column names as 'tmp' (with setNames
)
setNames(expand.grid(rep(list(0:1), length(tmp))), tmp)
# X1 X2 X3 X4
#1 0 0 0 0
#2 1 0 0 0
#3 0 1 0 0
#4 1 1 0 0
#5 0 0 1 0
#6 1 0 1 0
#7 0 1 1 0
#8 1 1 1 0
#9 0 0 0 1
#10 1 0 0 1
#11 0 1 0 1
#12 1 1 0 1
#13 0 0 1 1
#14 1 0 1 1
#15 0 1 1 1
#16 1 1 1 1
Upvotes: 1