Open In App

Convert List of Vectors to DataFrame in R

In this article, we will discuss how to convert the given list of vectors to Dataframe using the help of different functions in the R Programming Language.

For all the methods discussed below, few functions are common because of their functionality. Let us discuss them first.



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

Syntax: do.call(what, args, quote = FALSE, envir = parent.frame())



Parameters:

  • what:-either a function or a non-empty character string naming the function to be called.
  • args:a list of arguments to the function call. The names attribute of args gives the argument names.
  • quote:-a logical value indicating whether to quote the arguments.
  • envir:-an environment within which to evaluate the call.

Method 1: Using cbind()

cbind() function stands for column-bind. This function can be used to combine several vectors, matrices, or DataFrames by columns.

Syntax: cbind(x1, x2, …, deparse.level = 1)

In this approach, a single vector is considered as one column and then these columns are combined to form a dataframe.

Example:




my_list <- list(A =c(1,2,3,4,5), 
                B =c(6,7,8,9,10))
  
my_list
  
as.data.frame(do.call(cbind, my_list))   

Output:

Method 2: Using rbind()

rbind() function stands for row-bind. This function can be used to combine several vectors, matrices, or DataFrames by rows.

Syntax: rbind(x1, x2, …, deparse.level = 1)

Parameters:
x1, x2: vector, matrix, DataFrames
deparse.level: This value determines how the column names generated. The default value of deparse.level is 1.

In this approach, each vector is considered a row and then these rows are combined to form a dataframe.

Example:




my_list <- list(A =c(1,2,3,4,5), 
                B =c(6,7,8,9,10))
  
my_list
  
as.data.frame(do.call(rbind, my_list))   

Output:


Article Tags :