How to Convert R Vector to List

R Vector is a sequence of data items of the same data type. R List is a particular type of vector but can store mixed types. To check the data type of variable in R, use the typeof() function.

To create a vector in R, use the c() function. To create a list in R, use the list() function and pass the vector to the list() function, and it returns the list.

Convert R Vector to List

To convert Vector to List in R programming, use the as.list() function and pass the vector as a parameter, and it returns the list. The as.list() function convert objects to lists.

Syntax

as.list(x, ...)

Parameters

x: The object to convert to a list.

: Other named arguments (currently unused).

Example

rv <- 1:4

rl <- as.list(rv)
print(rl)

Output

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

You can see that

If you want to add a vector to other elements in a longer list, as.list() may not produce what you expect. For example, you want to add 3 text elements and a vector of five numeric elements (1:5), to make a list of 8 elements long.

data <- list("x", "y", "z", as.list(1:5))
print(data)

Output

[[1]]
[1] "x"

[[2]]
[1] "y"

[[3]]
[1] "z"

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

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

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

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

[[4]][[5]]
[1] 5

As you can see that it returns four elements which are x, y, z, list(1:5) which is not what we want. We want 8 different elements and to do that join two separate lists.

ls1 <- list("x", "y", "z")
ls2 <- as.list(1:5)
l <- c(ls1, ls2)
print(l)

Output

[[1]]
[1] "x"

[[2]]
[1] "y"

[[3]]
[1] "z"

[[4]]
[1] 1

[[5]]
[1] 2

[[6]]
[1] 3

[[7]]
[1] 4

[[8]]
[1] 5

You can see that now we get the eight individual elements of List as an output, which we wanted.

That is it for this vector to list tutorial in R lang.

See also

R Vector to data frame

R Vector to Matrix

Leave a Comment