简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM