15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Convert List to Vector in R (With Examples)

How to Convert List to Vector in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use one of the following methods to convert a list to a vector in R:

#use unlist() function
new_vector names = FALSE)

#use flatten_*() function from purrr library
new_vector 

The following examples show how to use each of these methods in practice with the following list:

#create list
my_list #display list
my_list

$A
[1] 1 2 3

$B
[1] 4 5

$C
[1] 6

Example 1: Convert List to Vector Using unlist() Function

The following code shows how to convert a list to a vector using the unlist() function:

#convert list to vector
new_vector #display vector
new_vector

A1 A2 A3 B1 B2  C 
 1  2  3  4  5  6 

Note that you can specify use.names = FALSE to remove the names from the vector:

#convert list to vector
new_vector names = FALSE)

#display vector
new_vector

[1] 1 2 3 4 5 6

Example 2: Convert List to Vector Using flatten_* Function

The following code shows how to convert a list to a vector using the family of flatten_* functions from the purrr package:

library(purrr) 

#convert list to vector
new_vector #display vector
new_vector

[1] 1 2 3 4 5 6

The flatten_dbl() function specifically converts the list to a vector of type double.

Note that we could use flatten_chr() to convert a character list to a vector of type character:

library(purrr) 

#define character list
my_char_list 
#convert character list to character vector
new_char_vector #display vector
new_char_vector

[1] "a" "b" "c" "d" "e" "f"

Check out this page for a complete list of the family of flatten_* functions.

Note: If you’re working with an extremely large list, the flatten_* functions will perform quicker than the unlist() function from base R.

Additional Resources

How to Convert List to a Data Frame in R
How to Convert Matrix to Vector in R
How to Convert Data Frame Column to Vector in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories