How to convert matrix to list in R Programming

 

Convert matrix to list in R

Conversion of a matrix into a list in Column-major order

The as.list() is an inbuilt function that takes an R language object as an argument and converts the object into a list. We have used this function to convert our matrix to a list. These objects can be Vectors, Matrices, Factors, and data frames. By default, as.list() converts the matrix to a list of lists in column-major order. 

Therefore, we have to use unlist() function to convert the list of lists to a single list. unlist() function in R Language is used to convert a list of lists to a single list, by preserving all the components.

Syntax: 

unlist(as.list(matrix))

Example:

mat = matrix(1:12,nrow=3, ncol=4)

  print("Sample matrix:")

print(mat)

  print("Matrix into a single list")

unlist(as.list(mat))

Conversion of a matrix into a list in Row-major order

For this approach we first have to find the transpose of the matrix In the code below, we have used t() function to calculate the transpose of our sample matrix. Due to which our matrix gets converted to a list in a Row-Major order.

The rest of the process is the same as above.

Syntax: 

unlist( as.list( t(mat) ))

mat = matrix(1:12,nrow=3, ncol=4)

  print("Sample matrix:")

print(mat)

  print("Result after conversion")

unlist(as.list(t(mat)))

Convert list to dataframe with specific column names in R

Converting with list data in the form of rows

do.call() method in R constructs and executes a function call from a name or a function and a list of arguments to be passed during the function call. 

Syntax: do.call (fun , args)

Arguments : 

·         fun – The function name to be executed

·         args – list of arguments to the function call

The rbind() method is used as the fun during this function call, which binds the passed elements of the list as rows of the dataframe. The rows are named based on the corresponding components of the list. Therefore, the argument of the do.call() method is the list object. The column names can be modified using the colnames() method in R, which assigns the column names to the assigned vector. In case, the length of the column names vector is smaller, NA is assigned as the respective column name. The column names are preserved in the original dataframe object. The number of columns in the dataframe is equivalent to the size of each component in the list. 

do.call ( rbind , list)

The as.data.frame() method is used to map the object to a dataframe consisting of rows and columns. 

# declaring a list object

lst_obj <- list(row1 = 1 : 5,row2 = LETTERS[1 : 5],row3 = FALSE)

 print ("Original List")

print (lst_obj)

 # binding columns together

df <- do.call(rbind, lst_obj)

print ("Original dataframe")

 # converting to a dataframe

data_frame <- as.data.frame(df)

print (data_frame)

 

print ("Modified dataframe")

colnames(data_frame) <- c(

  "ColA", "ColB", "ColC", "ColD", "ColE")

 

print (data_frame)

Column names can also be assigned to the dataframe based on the naming of elements inside the list object. The naming is assigned even if any one of the vector components is assigned names. 

# declaring a list object

lst_obj <- list("Row 1" = c(col1 = 'a', col2 = 'b',col3 = 'c'),"Row 2" = c(col1 = 'd', col2 = 'e',

                            col3 = 'f'))

 

print ("Original List")

print (lst_obj)

 

# binding columns together

df <- do.call(rbind, lst_obj)

print ("dataframe")

 # converting to a dataframe

data_frame <- as.data.frame(df)

print (data_frame)

Converting with list data in the form of columns

It can be done using the cbind() and do.call() method.

do.call ( cbind , list)

The following properties are maintained : 

·         The names assigned to the components of the list become column names, which can be modified using the colnames() method.

·         The total number of rows is equivalent to the length of the components.

·         Row names are mapped to the row numbers.

# declaring a list object

lst_obj <- list(col1 = 1 : 5,col2 = LETTERS[1 : 5],col3 = FALSE)

 print ("Original List")

print (lst_obj)

 # binding columns together

df <- do.call(cbind, lst_obj)

print ("dataframe")

 # converting to a dataframe

as.data.frame(df)

Convert list to array in R

A list can be converted to array in R by calling unlist( ) function with created list as parameter. Now pass the unlist() function into array() function as parameter, and use dim attribute for specifying number of rows, columns and matrices. unlist() converts list to vector.

 Syntax : 

array( unlist( list_variable ) , dim = ( rows ,columns , matrices ))

Given below are various implementation for the same:

Example 1 :

lst1=list(1:10)

 arr=array(unlist(lst1),dim=c(3,3,3))

print(arr)

 

Example 2:

lst1=list(c("karthik","nikhil","sravan"))

 arr=array(unlist(lst1),dim=c(1,3,3))

print(arr)

 

Example 3:

lst1=list(c("karthik","chandu","nandu"))

 arr=array(unlist(lst1),dim=c(1,3,2))

print(arr)

 

Comments

Popular posts from this blog

How to create Animated 3d chart with R.

Linux/Unix Commands frequently used

R Programming Introduction