R Program to create a list of data frames and access it from the list


March 12, 2022, Learn eTutorial
1109

How to create a list of data frames and access it from the list

Here we are explaining how to write an R program to create a list of data frames and access it from the list. Here we are using a built-in function list() for this. This function helps to create a list. The syntax of this function is 

list(…) 

Where ....(dots)are the objects, possibly named.

How to create a list of data frames and access it from the list using the R program

Below are the steps used in the R program to create a list of data frames and access it from the list. In this R program, we directly give the values to a built-in function list(). Here we are using variables DF1, DF2 for holding the data frames. Call the function list() with data frames for creating the list. Access the data frame from the list as like L[[1]], L[[2].

ALGORITHM

STEP 1: Assign variables DF1, DF2  with data frames

STEP 2: Create L list with 2 data frames as L= list(DF1, DF2)

STEP 3: Print the original lists

STEP 4: Access each data frame from the list as L[[1]], L[[2]]

STEP 5: Print each of the data frames

R Source Code

                                          DF1 = data.frame(y1 = c(0, 1, 2), y2 = c(3, 4, 5))
DF2 = data.frame(y1 = c(6, 7, 8), y2 = c(9, 10, 11))
L= list(DF1, DF2)
print("New list:")
print(L)
print("Data frame-1")
print(L[[1]])
print("Data frame-2")
print(L[[2]])
                                      

OUTPUT

[1] "New list:"
[[1]]
  y1 y2
1  0  3
2  1  4
3  2  5

[[2]]
  y1 y2
1  6  9
2  7 10
3  8 11

[1] "Data frame-1"
  y1 y2
1  0  3
2  1  4
3  2  5
[1] "Data frame-2"
  y1 y2
1  6  9
2  7 10
3  8 11