R Program to Convert a List to a Dataframe

Example 1: Convert List to Dataframe in R

# create a list 
list1 <- list(A = c("Sabby", "Cathy", "Dormy"),
  B = c(18, 24, 22),
  C = c("Computer Science", "Engineering", "Business")
)

# convert list to dataframe
result <- as.data.frame(list1)

print(result)

Output

    A  B                C
1 Sabby 18 Computer Science
2 Cathy 24      Engineering
3 Dormy 22         Business

In the above example, we have used the as.data.frame() function to convert the list named list1 to dataframe.

First, the names of the list A, B, C are converted to dataframe columns and finally all the list elements are added in each column respectively.


Example 2: Change Column Names While Convert to R Dataframe

In R, we pass the col.names parameter to change the name of the column. For example,

# create a list 
list1 <- list(A = c("Sabby", "Cathy", "Dormy"),
  B = c(18, 24, 22),
  C = c("Computer Science", "Engineering", "Business")
)

# convert list to dataframe and change name of column
result <- as.data.frame(list1, 
  col.names = c("Name", "Age", "Course")
)

print(result)

Output

    Name  Age                Course
1 Sabby 18 Computer Science
2 Cathy 24      Engineering
3 Dormy 22         Business

In the above example, we have passed the col.names parameter to the as.data.frame() function to change the name of each column.

result <- as.data.frame(list1, 
  col.names = c("Name", "Age", "Course")
)

Here, the list name

  • A in changed to "Name"
  • B in changed to "Age"
  • C in changed to "Course"

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges