Convert list to vector with unlist function in R

unlist function in R

unlist function in R, simply converts the list to vector with all the atomic components are being preserved.

Syntax for unlist function in R:

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

 

x List or data frame
recursive should unlisting be applied to all the components of list
use.names should  the names be preserved

 

Example of unlist function in R : convert list to vector

First let’s create a simple list:

# create list

a<-list(1,2,4,5,7)
is.list(a)
a

when we execute the above code the output will be

[1] TRUE

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 4

[[4]]
[1] 5

[[5]]
[1] 7

 

 

# Convert list to vector with unlist function in R

vector_a<-unlist(a)
vector_a

in the above example unlist function converts the list to vector so the output will be in vector.

[1] 1  2  4  5  7

 

Example of unlist function in R : convert data frame to vector

Lets use the default BOD data set to depict example of unlist function in r to convert data frame to vector

# Convert data frame to vector with R unlist function

a<- unlist(BOD)
a

The above code takes up BOD data frame and converts all the columns to vector as shown below

Time1 Time2 Time3 Time4 Time5 Time6 demand1 demand2 demand3 demand4
1.0      2.0       3.0       4.0      5.0       7.0         8.3          10.3          19.0          16.0
demand5 demand6
15.6          19.8

Now if we want to remove the names and print only the column values, we can use use.names = FALSE as an argument to unlist() function as shown below

# unlist a dataframe in R without column names

a<- unlist(BOD,use.names = FALSE)
a

so the output will only be column values without column names

[1]  1.0    2.0    3.0    4.0    5.0    7.0     8.3    10.3    19.0    16.0    15.6   19.8

previous unlist function in r                                                                                                                next small unlist function in r