# How to add a data frame inside a list in R?

R ProgrammingServer Side ProgrammingProgramming

A list may contain many objects such as vector, matrix, data frame, list etc. In this way, we can have access to all the necessary objects at the same time. If we want to add a data frame inside a list then we can use the length of the list. For example, if we have a list defined as List and we want to add a data frame df to the List then it can be added as follows −

List[[length(List)+1]]<−df

## Example1

df1<−data.frame(x=rnorm(20,1,0.004))
df1

## Output

   x
1 1.0103338
2 0.9959405
3 1.0018717
4 1.0056090
5 1.0014642
6 1.0042043
7 0.9939947
8 1.0021608
9 0.9993048
10 0.9972184
11 0.9912667
12 0.9964343
13 0.9979993
14 0.9935636
15 0.9990263
16 1.0002390
17 1.0004094
18 1.0034078
19 1.0044146
20 1.0026450
List1<−list(letters[1:26])
List1
[[1]]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"

List1[[length(List1)+1]]<−df1
List1

## Output

[[1]]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
[[2]]
x
1 1.0103338
2 0.9959405
3 1.0018717
4 1.0056090
5 1.0014642
6 1.0042043
7 0.9939947
8 1.0021608
9 0.9993048
10 0.9972184
11 0.9912667
12 0.9964343
13 0.9979993
14 0.9935636
15 0.9990263
16 1.0002390
17 1.0004094
18 1.0034078
19 1.0044146
20 1.0026450

## Example2

df2<−data.frame(x=rpois(20,4))
df2

## Output

x
1 1
2 2
3 5
4 3
5 9
6 5
7 4
8 5
9 5
10 5
11 6
12 4
13 5
14 1
15 2
16 5
17 5
18 3
19 4
20 6
List2<−list(sample(0:9,50,replace=TRUE))
List2
[[1]]
[1] 1 4 2 2 7 4 2 7 2 1 2 6 3 0 5 1 9 6 2 3 8 2 9 0 8 5 2 2 3 8 3 6 8 5 5 5 6 9
[39] 3 6 4 9 0 2 0 8 0 9 7 2

List2[[length(List2)+1]]<−df2
List2

## Output

[[1]]
[1] 1 4 2 2 7 4 2 7 2 1 2 6 3 0 5 1 9 6 2 3 8 2 9 0 8 5 2 2 3 8 3 6 8 5 5 5 6 9
[39] 3 6 4 9 0 2 0 8 0 9 7 2
[[2]]
x
1 1
2 2
3 5
4 3
5 9
6 5
7 4
8 5
9 5
10 5
11 6
12 4
13 5
14 1
15 2
16 5
17 5
18 3
19 4
20 6
Published on 07-Nov-2020 11:48:56