Convert list to dataframe with specific column names in R
A list contains different types of objects as their components. The components may belong to different data types or different dimensions. Vector can be useful components of a list and can be easily mapped as the rows or columns of a dataframe. Each column in the dataframe is referenced using a unique name, which can be either equivalent to the lists’ components names or assigned explicitly. In this article, we will discuss how to convert a list to dataframe with specific column names in R Programming Langauge.
Converting with list data in the form of rows
do.call() method in R constructs and executes a function call from a name or a function and a list of arguments to be passed during the function call.
Syntax: do.call (fun , args)
- fun – The function name to be executed
- args – list of arguments to the function call
The rbind() method is used as the fun during this function call, which binds the passed elements of the list as rows of the dataframe. The rows are named based on the corresponding components of the list. Therefore, the argument of the do.call() method is the list object. The column names can be modified using the colnames() method in R, which assigns the column names to the assigned vector. In case, the length of the column names vector is smaller, NA is assigned as the respective column name. The column names are preserved in the original dataframe object. The number of columns in the dataframe is equivalent to the size of each component in the list.
do.call ( rbind , list)
The as.data.frame() method is used to map the object to a dataframe consisting of rows and columns.
 "Original List" $col1  1 2 3 4 5 $col2  "A" "B" "C" "D" "E" $col3  FALSE  "Original dataframe" V1 V2 V3 V4 V5 row1 1 2 3 4 5 row2 A B C D E row3 FALSE FALSE FALSE FALSE FALSE  "Modified dataframe" ColA ColB ColC ColD ColE row1 1 2 3 4 5 row2 A B C D E row3 FALSE FALSE FALSE FALSE FALSE
Column names can also be assigned to the dataframe based on the naming of elements inside the list object. The naming is assigned even if any one of the vector components is assigned names.
 "Original List" $`Row 1` col1 col2 col3 "a" "b" "c" $`Row 2` col1 col2 col3 "d" "e" "f"  "dataframe" col1 col2 col3 Row 1 a b c Row 2 d e f
Converting with list data in the form of columns
It can be done using the cbind() and do.call() method.
do.call ( cbind , list)
The following properties are maintained :
- The names assigned to the components of the list become column names, which can be modified using the colnames() method.
- The total number of rows is equivalent to the length of the components.
- Row names are mapped to the row numbers.
 "Original List" $col1  1 2 3 4 5 $col2  "A" "B" "C" "D" "E" $col3  FALSE  "dataframe" col1 col2 col3 1 1 A FALSE 2 2 B FALSE 3 3 C FALSE 4 4 D FALSE 5 5 E FALSE