I have a list of the form list(c(x1,x2),y,c(z1,z2))
.
I want to combine the sub-elements of each element of the list to produce
a matrix of the form:
[1] x1 y z1
[2] x1 y z2
[3] x2 y z1
[4] x2 y z2
To give a concrete example, given:
A = list(c(1,4),2,3,c(1,4))
I'd like a function that will take A and produce an output that looks identical to what this command would produce:
t(matrix(c(c(1,2,3,1),1:4,c(4,2,3,1),c(4,2,3,4)),ncol=4))
Use expand.grid
:
expand.grid(A)
# Var1 Var2 Var3 Var4
# 1 1 2 3 1
# 2 4 2 3 1
# 3 1 2 3 4
# 4 4 2 3 4
and if the order really matters, you can do something like:
rev(expand.grid(rev(A)))
# Var4 Var3 Var2 Var1
# 1 1 2 3 1
# 2 1 2 3 4
# 3 4 2 3 1
# 4 4 2 3 4
and possibly rename the columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With