BarneyC - 1 year ago 56

R Question

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"))`

`> 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"

- gives a single row
`expand.grid(indVars)`

`> expand.grid(indVars)`

Var1 Var2 Var3 Var4

1 T.P T.M T.S E - gives 16 rows of all two variable combinations but doesn't do 3 or four
`expand.grid(indVars,indVars)`

*AND*where(so you get rows like`indVars[i]==indVars[i]`

`> expand.grid(indVars,indVars)[1,]`

Var1 Var2

1 T.P T.P - Logic says 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)`

`> expand.grid(indVars,indVars,indVars,indVars)[241,]`

Var1 Var2 Var3 Var4

241 T.P T.P E E

Answer Source

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"
```