Converting a List to Vector in R Language – unlist() Function

unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.

Syntax: unlist(list)

Parameters:
list: It is a list or Vector
use.name: Boolean value to prserve or not the position names

Example 1: Converting list numeric vector into a single vector

filter_none

edit
close

play_arrow

link
brightness_4
code

# R  program to illustrate
# converting list to vector
   
# Creating a list.
my_list <- list(l1 = c(1, 3, 5, 7),                
                l2 = c(1, 2, 3),                    
                l3 = c(1, 1, 10, 5, 8, 65, 90))   
   
# Apply unlist R function
print(unlist(my_list))                                    

chevron_right


Output:



l11 l12 l13 l14 l21 l22 l23 l31 l32 l33 l34 l35 l36 l37 
  1   3   5   7   1   2   3   1   1  10   5   8  65  90 

Here in the above code we have unlisted my_list using unlist() and convert it to a single vector.
As illustrated above, the list will dissolve and every element will be in the same line as shown above.

Example 2: Unlisting list with dataframe:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# Unlisting list with data frame
  
# Creating a list.
my_list <- list(l1 = c(1, 3, 5, 7),                
                l2 = c(1, 2, 3),                    
                l3 = c(1, 1, 10, 5, 8, 65, 90))   
   
  
# Create modified list
my_list_2 <- my_list 
  
# Add a data frame to the list                              
my_list_2[[4]] <- data.frame(x1 = c(1, 2, 3),       
                             x2 = c(4, 5, 6))
  
# Unlist list with data.frame
print(unlist(my_list_2, use.names = FALSE))
                          

chevron_right


Output:

[1]  1  3  5  7  1  2  3  1  1 10  5  8 65 90  1  2  3  4  5  6

Here in the above code we have modified the previous list and added new elements to “my_list_2” and used the function unlist() on it.
Also we set the “use.name” parameter to “FALSE” so we will not see the position names of the values in the vector.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.