Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert named list to vector with values only

Tags:

list

r

I have a list of named values:

myList <- list('A' = 1, 'B' = 2, 'C' = 3)

I want a vector with the value 1:3

I can't figure out how to extract the values without defining a function. Is there a simpler way that I'm unaware of?

library(plyr)
myvector <- laply(myList, function(x) x)

Is there something akin to myList$Values to strip the names and return it as a vector?

like image 894
sharoz Avatar asked Jun 13 '13 18:06

sharoz


People also ask

How do I turn a list into a vector?

To convert a list to a vector in R use unlist() function. This function takes a list as one of the arguments and returns a Vector.

How do I convert a value to a vector in R?

To convert List to Vector in R, use the unlist() function. The unlist() function simplifies to produce a vector by preserving all atomic components.

What does unlist () do in R?

unlist() function in R takes a list as an argument and returns a vector. A list in R contains heterogeneous elements meaning can contain elements of different types whereas a vector in R is a basic data structure containing elements of the same data type.


3 Answers

Use unlist with use.names = FALSE argument.

unlist(myList, use.names=FALSE) 
like image 191
Arun Avatar answered Sep 21 '22 12:09

Arun


purrr::flatten_*() is also a good option. the flatten_* functions add thin sanity checks and ensure type safety.

myList <- list('A'=1, 'B'=2, 'C'=3)  purrr::flatten_dbl(myList) ## [1] 1 2 3 
like image 23
hrbrmstr Avatar answered Sep 21 '22 12:09

hrbrmstr


This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))
like image 22
canevae Avatar answered Sep 20 '22 12:09

canevae