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
my_list < - list (l1 = c( 1 , 3 , 5 , 7 ),
l2 = c( 1 , 2 , 3 ),
l3 = c( 1 , 1 , 10 , 5 , 8 , 65 , 90 ))
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:
my_list < - list (l1 = c( 1 , 3 , 5 , 7 ),
l2 = c( 1 , 2 , 3 ),
l3 = c( 1 , 1 , 10 , 5 , 8 , 65 , 90 ))
my_list_2 < - my_list
my_list_2[[ 4 ]] < - data.frame(x1 = c( 1 , 2 , 3 ),
x2 = c( 4 , 5 , 6 ))
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.
Last Updated :
26 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...