Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine list elements in R

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))
like image 309
user1643809 Avatar asked Jan 20 '13 23:01

user1643809


1 Answers

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.

like image 160
flodel Avatar answered Sep 28 '22 16:09

flodel