In R you can use unlist() function for convert list to a vector.
The following method shows how you can do it with syntax.
Method 1: Use unlist() Function
unlist(list_name)
Let’s first create list with numeic values:
# Create list
lst <- list(A=c(12.39,11.25,12.15,13.48,13.78),B=c(78,89,85,84,81),C=c(5,7,1,2,7))
# Print list
print(lst)
Output:
$A
[1] 12.39 11.25 12.15 13.48 13.78
$B
[1] 78 89 85 84 81
$C
[1] 5 7 1 2 7
The output shows list with numeric values.
Use unlist() Function to Convert List to Vector
Now use unlist() function to convert list to a vector.
# Convert list to vector
v <- unlist(lst)
# Print vector
print(v)
Output:
A1 A2 A3 A4 A5 B1 B2 B3 B4 B5 C1 C2 C3 C4 C5
12.39 11.25 12.15 13.48 13.78 78.00 89.00 85.00 84.00 81.00 5.00 7.00 1.00 2.00 7.00
Here in the above code we created list using list() function after this we convert this list into vector using unlist() function.But in the above code we have names from vector.To remove names we can use use.names which is set as FALSE.
# Create list
lst <- list(A=c(12.39,11.25,12.15,13.48,13.78),B=c(78,89,85,84,81),C=c(5,7,1,2,7))
# Convert list to vector
v <- unlist(lst,use.names=FALSE)
# Print vector
print(v)
Output:
[1] 12.39 11.25 12.15 13.48 13.78 78.00 89.00 85.00 84.00 81.00 5.00 7.00 1.00 2.00 7.00
The output shows vector without vector names.
Use unlist() Function to List to Matrix
You can use convert list to matrix using unlist() function. Let’s see example for this:
# Create list
lst <- list(A=c(12.39,11.25,12.15),B=c(78,89,85),C=c(5,7,1))
# Convert list to matrix
m <- matrix(unlist(lst),ncol=3,byrow=TRUE)
# Print matrix
print(m)
Output:
[,1] [,2] [,3]
[1,] 12.39 11.25 12.15
[2,] 78.00 89.00 85.00
[3,] 5.00 7.00 1.00
The output shows matrix created using list.
This is how you can use unlist() function to convert list into vector or matrix.