R Program to convert a given list to vector

How to convert a given list to a vector

Here we are explaining how to write an R program to convert a given list to a vector. Here we are using a built-in function unlist() for this. This function helps to produce a vector that contains all the atomic components which occur in x. The syntax of this function is 

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

Where x is an R object, typically a list or vector. And recursive is logical, should unlisting be applied to list components of x and use.names are also logical which should name be preserved.

How to convert a given list to a vector in the R program

Below are the steps used in the R program to convert a given list to a vector. In this R program, we directly give the values to a built-in function unlist(). Here we are using variables l1,l2 for holding the list elements. Call the function unlist() for converting the two lists into vectors.Consider variables vec1,vce2 for holding converted vector values. Finally, add these two vectors and assigned them to variable V.And print the final vector.


STEP 1: Assign variables l1,l2  with a lists

STEP 2: Print the original lists

STEP 3:Converts the lists into vectors by calling unlist(l1) and unlist(l2)

STEP 4: Assign the converted vectors into the variables vec1,vec2

STEP 5: Print the vectors vec1,vec2 

STEP 6: Add the two vectors and assigned them to the variable V

STEP 7: Print the final vector V 


R Source Code

                                          l1 = list(1,2,3)
l2= list(4,5,6)
print("Original lists:")
print("Convert the lists to vectors:")
vec1 = unlist(l1)
vec2 = unlist(l2)
print("Add two vectors:")
V = vec1 + vec2
print("New vector:")


[1] "Original lists:"
[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

[1] 6

[1] "Convert the lists to vectors:"
[1] 1 2 3
[1] 4 5 6
[1] "Add two vectors:"
[1] "New vector:"
[1] 5 7 9