Creating a Dataframe from a List using do.call()
R
# Sample list my_list <- list ( StudentID = c (101, 102, 103, 104), FirstName = c ( "Alice" , "Bob" , "Charlie" , "David" ), LastName = c ( "Smith" , "Johnson" , "Brown" , "Lee" ), Score = c (95, 88, 75, 92) ) # Convert the list to a dataframe my_dataframe <- do.call (data.frame, my_list) # Print the resulting dataframe print (my_dataframe) |
Output:
StudentID FirstName LastName Score
1 101 Alice Smith 95
2 102 Bob Johnson 88
3 103 Charlie Brown 75
4 104 David Lee 92
The do.call function is used to apply the data.frame constructor to the elements of my_list, effectively converting the list into a dataframe.
In this example, we have a list named ‘my_list’ containing information about students, including their StudentID, FirstName, LastName, and Score. The code uses do.call to convert this list into a dataframe called my_dataframe. The resulting dataframe will have columns corresponding to the elements of the list, and the data will be populated accordingly.
- ‘my_list’ is defined as a list containing four components: StudentID, FirstName, LastName, and Score. Each of these components is a vector containing data.
- do.call is used to convert the ‘my_list’ into a dataframe. It essentially applies the data.frame function to the elements of my_list. This results in the creation of a dataframe named my_dataframe.
How to Convert a List to a Dataframe in R
We have a list of values and if we want to Convert a List to a Dataframe within it, we can use a as.data.frame. it Convert a List to a Dataframe for each value. A DataFrame is a two-dimensional tabular data structure that can store different types of data. Various functions and packages, such as data.frame(), as.data.frame(), and the dplyr package, can be employed to achieve this conversion. In this article, we will discuss how to Convert a List to a Dataframe with its working example in the R Programming Language.