How to combine vectors of equal length into a list with corresponding elements representing a single element of the list in R?


To combine three vectors into a list with corresponding elements representing a single element of the list we can use mapply function. For example, if we have three vectors x, y, and z each having number of elements equal to one-hundred then the list with corresponding elements can be created by using mapply(c,x,y,z,SIMPLIFY=FALSE).

Example

 Live Demo

x1<-1:20
y1<-1:20
z1<-20:1
mapply(c,x1,y1,z1,SIMPLIFY=FALSE)

Output

[[1]]
[1] 1 1 20
[[2]]
[1] 2 2 19
[[3]]
[1] 3 3 18
[[4]]
[1] 4 4 17
[[5]]
[1] 5 5 16
[[6]]
[1] 6 6 15
[[7]]
[1] 7 7 14
[[8]]
[1] 8 8 13
[[9]]
[1] 9 9 12
[[10]]
[1] 10 10 11
[[11]]
[1] 11 11 10
[[12]]
[1] 12 12 9
[[13]]
[1] 13 13 8
[[14]]
[1] 14 14 7
[[15]]
[1] 15 15 6
[[16]]
[1] 16 16 5
[[17]]
[1] 17 17 4
[[18]]
[1] 18 18 3
[[19]]
[1] 19 19 2
[[20]]
[1] 20 20 1

Example

 Live Demo

x2<-rnorm(20)
y2<-rnorm(20)
z2<-rnorm(20)
a2<-rnorm(20)
b2<-rnorm(20)
mapply(c,x2,y2,z2,a2,b2,SIMPLIFY=FALSE)

Output

[[1]]
[1] 0.88030917 -0.15681801 -0.71128117 -0.06484493 0.02902034
[[2]]
[1] -1.0189866 0.2922982 1.0829246 1.1930435 -0.4582951
[[3]]
[1] -0.59622712 -0.48214712 0.08316515 1.74253306 -0.04677903
[[4]]
[1] -0.6714311 -1.5970019 -0.1486865 0.6280077 -1.6230396
[[5]]
[1] -0.31790639 1.02929693 -0.98422633 -1.18992473 0.08402105
[[6]]
[1] 0.06655424 -2.12189071 1.23338511 -1.58198753 -0.82106071
[[7]]
[1] 0.3982578 2.4086283 0.6761518 -1.6721258 -0.8722924
[[8]]
[1] 0.0231563 0.9067107 -0.3208233 0.3420389 -0.8405606
[[9]]
[1] -0.5325169 0.6372508 0.9362706 1.7724822 0.1934017
[[10]]
[1] -0.03718933 -1.51224275 0.22590754 -0.68509725 -0.05675418
[[11]]
[1] 0.6721130 -0.0163331 -1.2063054 -0.6187888 -0.9994600
[[12]]
[1] -0.63104688 0.08017714 -0.01677552 -1.32654309 -0.28477733
[[13]]
[1] -0.7466293 -1.0290986 0.1239188 0.5020038 -0.6060167
[[14]]
[1] -1.03619822 -0.01400334 -1.24066001 -0.14693990 0.84074405
[[15]]
[1] -1.1087838 0.4577026 -0.1660513 0.4572123 0.1333066
[[16]]
[1] 0.4870503 0.8694689 0.4490408 0.5883133 -0.3761401
[[17]]
[1] 0.08145911 1.12753332 -1.26155664 -1.22535972 -0.75051785
[[18]]
[1] 0.4706167 -0.8978908 -1.3874243 -0.1189644 0.1072799
[[19]]
[1] 0.4461086 -0.5202976 1.0085317 -0.3409258 0.4308268
[[20]]
[1] -0.4163482 -0.2803990 0.2045526 1.2416159 -0.1843258

Example

 Live Demo

x3<-rpois(20,5)
y3<-rpois(20,5)
z3<-rpois(20,5)
mapply(c,x3,y3,z3,SIMPLIFY=FALSE)

Output

[[1]]
[1] 4 4 5
[[2]]
[1] 2 3 4
[[3]]
[1] 9 7 5
[[4]]
[1] 3 2 4
[[5]]
[1] 7 2 3
[[6]]
[1] 1 4 3
[[7]]
[1] 5 6 5
[[8]]
[1] 8 4 2
[[9]]
[1] 7 1 4
[[10]]
[1] 7 4 4
[[11]]
[1] 7 8 5
[[12]]
[1] 3 3 3
[[13]]
[1] 3 1 2
[[14]]
[1] 2 2 7
[[15]]
[1] 8 7 6
[[16]]
[1] 7 7 4
[[17]]
[1] 5 5 11
[[18]]
[1] 6 7 6
[[19]]
[1] 6 7 2
[[20]]
[1] 6 7 7

Updated on: 08-Dec-2020

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements