Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create combination of multiple vectors in R?
To create combination of multiple vectors, we can use expand.grid function. For example, if we have six vectors say x, y, z, a, b, and c then the combination of vectors can be created by using the command expand.grid(x,y,z,a,b,c).
Example
x1<-rpois(2,1) x2<-rpois(2,1) x3<-rpois(2,1) x4<-rpois(2,1) expand.grid(x1,x2,x3,x4)
Output
Var1 Var2 Var3 Var4 1 1 2 2 1 2 1 2 2 1 3 1 0 2 1 4 1 0 2 1 5 1 2 1 1 6 1 2 1 1 7 1 0 1 1 8 1 0 1 1 9 1 2 2 2 10 1 2 2 2 11 1 0 2 2 12 1 0 2 2 13 1 2 1 2 14 1 2 1 2 15 1 0 1 2 16 1 0 1 2
Example
y1<-rpois(2,2) y2<-rpois(2,2) y3<-rpois(2,2) y4<-rpois(2,2) y5<-rpois(2,2) expand.grid(y1,y2,y3,y4,y5)
Output
Var1 Var2 Var3 Var4 Var5 1 4 0 1 1 1 2 1 0 1 1 1 3 4 2 1 1 1 4 1 2 1 1 1 5 4 0 2 1 1 6 1 0 2 1 1 7 4 2 2 1 1 8 1 2 2 1 1 9 4 0 1 1 1 10 1 0 1 1 1 11 4 2 1 1 1 12 1 2 1 1 1 13 4 0 2 1 1 14 1 0 2 1 1 15 4 2 2 1 1 16 1 2 2 1 1 17 4 0 1 1 4 18 1 0 1 1 4 19 4 2 1 1 4 20 1 2 1 1 4 21 4 0 2 1 4 22 1 0 2 1 4 23 4 2 2 1 4 24 1 2 2 1 4 25 4 0 1 1 4 26 1 0 1 1 4 27 4 2 1 1 4 28 1 2 1 1 4 29 4 0 2 1 4 30 1 0 2 1 4 31 4 2 2 1 4 32 1 2 2 1 4
Example
z1<-sample(LETTERS[1:26],2) z2<-sample(LETTERS[1:26],2) z3<-sample(LETTERS[1:26],2) z4<-sample(LETTERS[1:26],2) z5<-sample(LETTERS[1:26],2) expand.grid(z1,z2,z3,z4,z5)
Output
Var1 Var2 Var3 Var4 Var5 1 Q K U S Q 2 I K U S Q 3 Q C U S Q 4 I C U S Q 5 Q K L S Q 6 I K L S Q 7 Q C L S Q 8 I C L S Q 9 Q K U T Q 10 I K U T Q 11 Q C U T Q 12 I C U T Q 13 Q K L T Q 14 I K L T Q 15 Q C L T Q 16 I C L T Q 17 Q K U S P 18 I K U S P 19 Q C U S P 20 I C U S P 21 Q K L S P 22 I K L S P 23 Q C L S P 24 I C L S P 25 Q K U T P 26 I K U T P 27 Q C U T P 28 I C U T P 29 Q K L T P 30 I K L T P 31 Q C L T P 32 I C L T P
Advertisements
