Convert an Object to List in R Programming – as.list() Function
as.list() function in R Programming Language is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and dataframes.
Syntax: as.list(object)
Parameters:
object: Vector, Matrix, factor, or data frame
R – as.list() Function Example
Example 1: Converting Vector to list using as.list() function in R Language
R
# R program to convert object to list# Creating vectorx < - c(1, 2, 3, 4, 5)# Calling as.list() Functionas.list(x) |
Output:
[[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3 [[4]] [1] 4 [[5]] [1] 5
Example 2: Converting data frame to list using as.list() function in R Language
R
# R program to convert object to list# Calling pre-defined data setBOD# Calling as.list() Functionas.list(BOD) |
Output:
Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4 4 16.0 5 5 15.6 6 7 19.8 $Time [1] 1 2 3 4 5 7 $demand [1] 8.3 10.3 19.0 16.0 15.6 19.8 attr(, "reference") [1] "A1.4, p. 270"
Example 3: Converting matrix to list using as.list() function in R Language
R
# R program to create a matrix# and then convert into listA = matrix( # Taking sequence of elementsc(1, 2, 3, 4, 5, 6, 7, 8, 9),# No of rowsnrow = 3,# No of columnsncol = 3, # By default matrices are in column-wise order# So this parameter decides how to arrange the matrixbyrow = TRUE )# Naming rowsrownames(A) = c("a", "b", "c")# Naming columnscolnames(A) = c("c", "d", "e")cat("The 3x3 matrix:\n")print(A)lst = as.list(A)lst |
Output:
The 3x3 matrix: c d e a 1 2 3 b 4 5 6 c 7 8 9 [[1]] [1] 1 [[2]] [1] 4 [[3]] [1] 7 [[4]] [1] 2 [[5]] [1] 5 [[6]] [1] 8 [[7]] [1] 3 [[8]] [1] 6 [[9]] [1] 9





Please Login to comment...