Open In App

Create Matrix and Data Frame from Lists in R Programming

Last Updated : 01 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In R programming, there 5 basic objects. Lists are the objects that can contain heterogeneous types of elements, unlike vectors. Matrices can contain the same type of elements or homogeneous elements. On the other hand, data frames are similar to matrices but have an advantage over matrices to keep heterogeneous elements. In this article, we’ll learn to create matrix and data frame using lists.

Create Matrix using List

Matrices are created using matrix() function in R programming. Another function that will be used is unlist() function to convert the lists into a vector. The vector created contains atomic components of the given list.

Syntax:
unlist(x, recursive = TRUE, use.names = TRUE)

Parameters:

x: represents list
recursive: represents logical value. If FALSE, function will not recurse beyond first level of list
use.names: represents logical value to preserve the naming information

Example 1:




# Defining list
ls1 <- list(
  list(1, 2, 3),
  list(4, 5, 6))
  
# Print list
cat("The list is:\n")
print(ls1)
cat("Class:", class(ls1), "\n")
  
# Convert list to matrix
mt1 <- matrix(unlist(ls1), nrow = 2, byrow = TRUE)
  
# Print matrix
cat("\nAfter conversion to matrix:\n")
print(mt1)
cat("Class:", class(mt1), "\n")


Output:

The list is:
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3


[[2]]
[[2]][[1]]
[1] 4

[[2]][[2]]
[1] 5

[[2]][[3]]
[1] 6

Class: list 

After conversion to matrix:
     [, 1] [, 2] [, 3]
[1, ]    1    2    3
[2, ]    4    5    6

Class: matrix 

Example 2:




# Defining list
ls2 <- list("A", 10, TRUE, 2i)
  
# Print list
cat("\nThe list is:\n")
print(ls2)
cat("Class:", class(ls2), "\n")
  
# Convert list to matrix
mt2 <- matrix(unlist(ls2), nrow = 2, byrow = TRUE)
  
# Print matrix
cat("\nAfter conversion to matrix:\n")
print(mt2)
cat("Class:", class(mt2), "\n")
cat("\nType:", typeof(mt2), "\n")


Output:

The list is:
[[1]]
[1] "A"

[[2]]
[1] 10

[[3]]
[1] TRUE

[[4]]
[1] 0+2i

Class: list

After conversion to matrix:
     [, 1]   [, 2]  
[1, ] "A"    "10"  
[2, ] "TRUE" "0+2i"

Class: matrix 

Type: character

Create Dataframe using List

In the same way, dataframe can be created using lists by using unlist() function and data.frame() function.

Example:




# Defining lists
n <- list(1:3)
l <- list(letters[1:3])
m <- list(month.name[1:3])
  
# Convert lists into dataframe columns
df <- data.frame(unlist(n), unlist(l), unlist(m))
  
# Names of columns of dataframe
names(df) <- c("Number", "Letters", "Month")
  
# Print dataframe
cat("The dataframe is :\n")
print(df)


Output:

The dataframe is :
  Number Letters    Month
1      1       a  January
2      2       b February
3      3       c    March


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads