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

Example

> df1$z<-list(1:3,4:5,6:10,12:15,16:17,18:20,21:22,23:25,26:27,28:30,31:35,36:38,39:42,43:45,46:48,49:55,56:60,61:62,63:65,66:70)
> df1

Output

  x y z
1 6 1            1, 2, 3
2 8 1            4, 5
3 6 2      6, 7, 8, 9, 10
4 8 1      12, 13, 14, 15
5 5 1          16, 17
6 3 1          18, 19, 20
7 6 1          21, 22
8 7 1          23, 24, 25
9 7 1          26, 27
10 7 2         28, 29, 30
11 5 0     31, 32, 33, 34, 35
12 5 2         36, 37, 38
13 2 2         39, 40, 41, 42
14 4 0         43, 44, 45
15 2 1         46, 47, 48
16 3 1 49, 50, 51, 52, 53, 54, 55
17 4 0     56, 57, 58, 59, 60
18 6 4         61, 62
19 6 2     63, 64, 65
20 4 1     66, 67, 68, 69, 70

Let’s have a look at another example:

Example

> df2<-data.frame(F1=sample(LETTERS[1:4],20,replace=TRUE),F2=sample(LETTERS[21:26],20,replace=TRUE))
> df2

Output

F1 F2
1 C W
2 B Z
3 A V
4 D W
5 D V
6 A X
7 C X
8 D Y
9 C Y
10 B V
11 D X
12 B W
13 D V
14 A U
15 A X
16 C X
17 C Z
18 B X
19 C Z
20 A V

Example

> df2$F3<-list(rep(c("A","B")))
> 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
raja
Published on 21-Nov-2020 09:33:49
Advertisements