How to Convert R List to data frame

There are many circumstances in R where you want to convert a list of vectors into a data frame. In this tutorial, we will see how to convert a list to a data frame.

Convert R List to data frame

To convert a list to data frame in R, use the as.data.frame() function. The as.data.frame() function is used to check if an object is a data frame and if it is not, then as.data.frame() function will try to coerce it if possible. The as.data.frame() function takes a list as a parameter, consisting of vectors, and returns the data frame.

Syntax

as.data.frame(x, row.names = NULL, optional = FALSE, …)

Parameters

x: It is any R object.

row.names:  It is NULL or a character vector giving the row names for the data frame. Missing values are not allowed.

optional: It is logical. If TRUE, setting row names and converting column names.

Example

app_list <- list(
 s1 = c(1, 3, 8),
 s2 = c(2, 4, 6),
 s3 = c(11, 21, 19))

app_list

cat("After converting list to data frame", "\n")
as.data.frame(app_list)

Output

$s1
[1] 1 3 8

$s2
[1] 2 4 6

$s3
[1] 11 21 19

After converting list to data frame
   s1 s2 s3
1  1  2  11
2  3  4  21
3  8  6  19

In this example, first, we have defined a list that consists of three numeric vectors.

Then use the as.data.frame() method to convert the list to data frame. The default for the parameter stringsAsFactors is now the default.stringsAsFactors() which in turn yields FALSE as its default.

Leave a Comment