# How to create a data frame in R with list elements?

R ProgrammingServer Side ProgrammingProgramming

If a list has the same length of elements (not sub-elements) as the length of each vector for which we want to create the data frame then we first need to create the data frame of vectors then we can easily add the list into the data frame. But if we have a list and other vectors then data frame cannot be created as data.frame function will read each value of the list separately.

## Example

Live Demo

> df1<-data.frame(x=rpois(20,5),y=rpois(20,1))
> df1

## Output

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

> df2

## Output

  F1 F2 F3
1 C W A, B
2 B Z A, B
3 A V A, B
4 D W A, B
5 D V A, B
6 A X A, B
7 C X A, B
8 D Y A, B
9 C Y A, B
10 B V A, B
11 D X A, B
12 B W A, B
13 D V A, B
14 A U A, B
15 A X A, B
16 C X A, B
17 C Z A, B
18 B X A, B
19 C Z A, B
20 A V A, B
Published on 21-Nov-2020 05:03:49