Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 26 May, 2020

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




# 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))                                    

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:




# 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))
                          

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 Articles
Page :

Start Your Coding Journey Now!