BarneyC BarneyC - 3 months ago 13
R Question

r expand.grid to give every combination - not as expected

I'm not even sure how to give this a better, and not obviously duplicate type, title but I think this is a different question about expand.grid.

I have a list of variables for which I need a data.frame or list of every possible combination to feed into a bit of ordinal regression.

The list:

> indVars <- as.list(c("T.P","T.M","T.S","E"))


Desired output:

> out List of (?)
: "T.P"
: "T.M"
: "T.S"
: "E"
: "T.P" "T.M"
: "T.P" "T.S"
: "T.P" "E"
.
.
.
: "T.P" "T.M" "T.S" "E"


Attempted:


  1. expand.grid(indVars)
    gives a single row

    > expand.grid(indVars)
    Var1 Var2 Var3 Var4
    1 T.P T.M T.S E

  2. expand.grid(indVars,indVars)
    gives 16 rows of all two variable combinations but doesn't do 3 or four AND where
    indVars[i]==indVars[i]
    (so you get rows like

    > expand.grid(indVars,indVars)[1,]
    Var1 Var2
    1 T.P T.P

  3. Logic says
    expand.grid(indVars,indVars,indVars,indVars)
    to give all up to combinations (256 of them) but again you end up with rows with multiple instances of the same indVar. For example:

    > expand.grid(indVars,indVars,indVars,indVars)[241,]
    Var1 Var2 Var3 Var4
    241 T.P T.P E E



Request: Can someone point out how to expand this list of 4 variables into every combination of 1,2,3 and 4 of them with no duplicates?

Answer

Possibly this is an XY problem and there is a better aproach to do the ordinal regression.

I suspect that order doesn't matter. Use combn:

res <- lapply(seq_along(indVars), combn, x = indVars, simplify = FALSE)
unlist(res, FALSE)

# [[1]]
# [1] "T.P"
# 
# [[2]]
# [1] "T.M"
# 
# [[3]]
# [1] "T.S"
# 
# [[4]]
# [1] "E"
# 
# [[5]]
# [1] "T.P" "T.M"
# 
# [[6]]
# [1] "T.P" "T.S"
# 
# [[7]]
# [1] "T.P" "E"  
# 
# [[8]]
# [1] "T.M" "T.S"
# 
# [[9]]
# [1] "T.M" "E"  
# 
# [[10]]
# [1] "T.S" "E"  
# 
# [[11]]
# [1] "T.P" "T.M" "T.S"
# 
# [[12]]
# [1] "T.P" "T.M" "E"  
# 
# [[13]]
# [1] "T.P" "T.S" "E"  
# 
# [[14]]
# [1] "T.M" "T.S" "E"  
# 
# [[15]]
# [1] "T.P" "T.M" "T.S" "E"