How to Convert R List to Vector

R List is an inbuilt data structure containing various data types like vectors, strings, numbers, and another list. The list can be created using the list() function in R.

R Vector is an inbuilt data structure that contains elements of the same type. The same data type can be strings, numbers, vectors, or complex.

How to Create List in R

To create a list in R, use the list() function. A list is a generic vector containing other objects. To check the data type of any variable in R language, use the typeof() function.

app_list <- list(
 s1 = c(1, 3, 8),
 s2 = c(2, 4, 6),
 s3 = c(11, 21, 19))

Output

$s1
[1] 1 3 8

$s2
[1] 2 4 6

$s3
[1] 11 21 19

How to Create Vector in R

To create a vector in R, use the c() function. If you try to define a vector with different data types, the c() function will try and coerce elements to the same type.

rv <- c(11, 19, 21, 18, 46)
rv

Output

[1] 11 19 21 18 46

Convert R List to Vector

To convert List to Vector in R, use the unlist() function. The unlist() function simplifies to produce a vector by preserving all atomic components.

Syntax

unlist(x, recursive = TRUE, use.names = TRUE)

Arguments

list

The unlist() function takes a list as a required parameter, which then will be converted into the vector.

recursive

This is an optional argument that is logical and only accepts TRUE or FALSE.

use.names

This is an optional argument that is logical and accepts TRUE or FALSE.

Example of conversion: List to Vector in R

Define a list using the list() function.

app_list <- list(1, 2, 3, 4)
app_list

Output

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

To convert list to vector, apply the unlist() function.

app_list <- list(1, 2, 3, 4)
app_list
cat("After converting list to vector", "\n")
unlist(app_list)

Output

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

After converting list to vector

[1] 1 2 3 4

Here, you can see that we got the vector from the list.

Converting list numeric vector into a single vector

Define a numeric list vector and then convert it into a single vector.

app_list <- list(
 s1 = c(1, 3, 8),
 s2 = c(2, 4, 6),
 s3 = c(11, 21, 19))

app_list

cat("After converting list to vector", "\n")
unlist(app_list)

Output

$s1
[1] 1 3 8

$s2
[1] 2 4 6

$s3
[1] 11 21 19

After converting list to vector

s11 s12 s13 s21 s22 s23 s31 s32 s33
 1   3   8   2   4   6   11  21 19

You can see that the unlist() function converts it to a single vector.

Conclusion

Converting one data type to another is the common operation in R programming. If you want to convert the list to vector, then use the unlist() function. That is it for this tutorial.

See also

R List to String

R as.numeric()

Leave a Comment