How to combine two lists of same size to make a data frame in R?

R ProgrammingServer Side ProgrammingProgramming

If we have two lists of same size then we can create a data frame using those lists and this can be easily done with the help of expand.grid function. The expand.grid function create a data frame from all combinations of the provided lists or vectors or factors. For example, if we have two lists defined as List1 and List2 then we can create a data frame using the code expand.grid(List1,List2).

Example

 Live Demo

Consider the below lists −

List1<-as.list(sample(LETTERS[1:5],5,replace=TRUE))
List1

Output

[[1]]
[1] "C"
[[2]]
[1] "D"
[[3]]
[1] "E"
[[4]]
[1] "D"
[[5]]
[1] "D"

Example

 Live Demo

List2<-as.list(sample(LETTERS[6:10],5,replace=TRUE))
List2

Output

[[1]]
[1] "I"
[[2]]
[1] "J"
[[3]]
[1] "F"
[[4]]
[1] "I"
[[5]]
[1] "F"

Creating a data frame using List1 and List2 −

Example

df1<-expand.grid(List1,List2)
df1

Output

  Var1 Var2
1  C I
2  D I
3  E I
4  D I
5  D I
6  C J
7  D J
8  E J
9  D J
10 D J
11 C F
12 D F
13 E F
14 D F
15 D F
16 C I
17 D I
18 E I
19 D I
20 D I
21 C F
22 D F
23 E F
24 D F
25 D F

Let’s have a look at another example −

Example

 Live Demo

List3<-as.list(c("India","China","USA","France","Germany"))
List3

Output

[[1]]
[1] "India"
[[2]]
[1] "China"
[[3]]
[1] "USA"
[[4]]
[1] "France"
[[5]]
[1] "Germany"

Example

 Live Demo

List4<-as.list(1:4)
List4

Output

[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 4

Creating a data frame using List3 and List4 −

Example

df2<-expand.grid(List3,List4)
df2

Output

Var1 Var2
1 India 1
2 China 1
3 USA 1
4 France 1
5 Germany 1
6 India 2
7 China 2
8 USA 2
9 France 2
10 Germany 2
11 India 3
12 China 3
13 USA 3
14 France 3
15 Germany 3
16 India 4
17 China 4
18 USA 4
19 France 4
20 Germany 4
raja
Updated on 17-Oct-2020 13:32:11

Advertisements