w3resource

R Programming: Create a List of DataFrames and access each DataFrame

R Programming: List Exercise-10 with Solution

Write a R program to create a list of dataframes and access each of those data frames from the list.

Sample Solution :

R Programming Code :

 # Create the first dataframe with columns y1 and y2
df1 = data.frame(y1 = c(0, 1, 2), y2 = c(3, 4, 5))

# Create the second dataframe with columns y1 and y2
df2 = data.frame(y1 = c(6, 7, 8), y2 = c(9, 10, 11))

# Combine the two dataframes into a list
new_list = list(df1, df2)

# Print a message indicating the new list
print("New list:")

# Print the new list containing the dataframes
print(new_list)

# Print a message indicating the first dataframe
print("Data frame-1")

# Print the first dataframe from the list
print(new_list[[1]])

# Print a message indicating the second dataframe
print("Data frame-2")

# Print the second dataframe from the list
print(new_list[[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                         

Explanation:

  • Create DataFrames:
    • df1 is a dataframe with two columns: y1 and y2. The values in y1 are 0, 1, and 2, and the values in y2 are 3, 4, and 5.
    • df2 is another dataframe with the same columns: y1 and y2. The values in y1 are 6, 7, and 8, and the values in y2 are 9, 10, and 11.
  • Combine DataFrames into a List:
    • new_list is a list that contains df1 and df2 as its elements.
  • Print Statements:
    • Print "New list:" to indicate the following output will display the list of dataframes.
    • Print new_list to show the entire list containing both dataframes.
    • Print "Data frame-1" to label the output of the first dataframe in the list.
    • Print new_list[[1]] to show the first dataframe (df1).
    • Print "Data frame-2" to label the output of the second dataframe in the list.
    • Print new_list[[2]] to show the second dataframe (df2).

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to convert a given list to vector.
Next: Write a R program to count number of objects in a given list.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/list/r-programming-list-exercise-10.php