as.list() in R: How to Convert R Object to List in R

The list() is a function used to construct, coerce, and check for both kinds of R lists. All lists within R are Generic Vectors. The list() function returns a list of dotted pair lists composed of its arguments with each value either tagged or untagged, depending on how the argument was specified.

as.list() in R

The as.list() is a built-in R function that converts objects to lists. The as.list() function is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames.

Syntax

as.list(object)

Parameters

The as.list() function takes an object as a parameter, a vector, matrix, factor, or data frame.

Example

Passing a vector as a parameter to the as.list() function.

rv <- 1:5
rv
cat("After converting a vector to list", "\n")
rl <- as.list(rv)
rl

Output

[1] 1 2 3 4 5
After converting a vector to list
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

This is the conversion of vector to list.

Converting data frame to list using as.list() function

R provides a built-in data set that we can use to create a data frame and then use the as.list() function to convert the data frame into the list.

data("ToothGrowth")

df <- head(ToothGrowth)
df
cat("After converting a data frame to list", "\n")
rl <- as.list(df)
rl

Output

   len supp dose
1  4.2  VC  0.5
2  11.5 VC  0.5
3  7.3  VC  0.5
4  5.8  VC  0.5
5  6.4  VC  0.5
6  10.0 VC  0.5
After converting a data frame to list
$len
[1] 4.2 11.5 7.3 5.8 6.4 10.0

$supp
[1] VC VC VC VC VC VC
Levels: OJ VC

$dose
[1] 0.5 0.5 0.5 0.5 0.5 0.5

Converting matrix to list using as.list() function

To convert a matrix to list, use the as.list() function.

vt <- c("Millie", "Noah", "Finn", "Sadie")
mtrx <- matrix(vt, nrow = 2, ncol = 2)
mtrx
cat("After converting a matrix to list", "\n")
rl <- as.list(mtrx)
rl

Output

       [,1]    [,2]
[1,]  "Millie"  "Finn"
[2,]  "Noah"    "Sadie"
After converting a matrix to list
[[1]]
[1] "Millie"

[[2]]
[1] "Noah"

[[3]]
[1] "Finn"

[[4]]
[1] "Sadie"

Converting a factor to list using as.list() function

To create a factor in R, use the factor() method. To convert a factor to a list, use the as.list() function.

rv <- c("Millie", "Noah")
rf <- factor(rv)
rf
cat("After converting a factor to list", "\n")
rl <- as.list(rf)
rl

Output

[1] Millie Noah
Levels: Millie Noah
After converting a factor to list
[[1]]
[1] Millie
Levels: Millie Noah

[[2]]
[1] Noah
Levels: Millie Noah

That is it for this tutorial.

See also

R Matrix to List

R Matrix to Vector

R Vector to String

Leave a Comment