Create Matrix and Data Frame from Lists in R Programming
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:
ls1 < - list (
list ( 1 , 2 , 3 ),
list ( 4 , 5 , 6 ))
cat( "The list is:\n" )
print (ls1)
cat( "Class:" , class (ls1), "\n" )
mt1 < - matrix(unlist(ls1), nrow = 2 , byrow = TRUE)
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:
ls2 < - list ( "A" , 10 , TRUE, 2i )
cat( "\nThe list is:\n" )
print (ls2)
cat( "Class:" , class (ls2), "\n" )
mt2 < - matrix(unlist(ls2), nrow = 2 , byrow = TRUE)
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:
n < - list ( 1 : 3 )
l < - list (letters[ 1 : 3 ])
m < - list (month.name[ 1 : 3 ])
df < - data.frame(unlist(n), unlist(l), unlist(m))
names(df) < - c( "Number" , "Letters" , "Month" )
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
Last Updated :
01 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...