Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to melt a list into a vector?

Tags:

r

I'd like to melt this:

test = list( one = "joe" , two = c( "john" , "jane" ) )

Into a character vector:

c( "joe" , "john" , "jane" )

I tried melt() in the reshape package, but that results in a data.frame where strings are treated as factors, so I'd have to do something like:

as.character( melt( test )$value )

Is there a shorter/faster way?

like image 641
SFun28 Avatar asked Aug 25 '11 20:08

SFun28


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.

What is the difference between a vector and a list in R?

A list holds different data such as Numeric, Character, logical, etc. Vector stores elements of the same type or converts implicitly. Lists are recursive, whereas vector is not. The vector is one-dimensional, whereas the list is a multidimensional object.

How do I convert a list to a Dataframe in R?

Convert List to DataFrame using data. data. frame() is used to create a DataFrame in R that takes a list, vector, array, etc as arguments, Hence, we can pass a created list to the data. frame() function to convert list to DataFrame. It will store the elements in a single row in the DataFrame.

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.


1 Answers

unlist(test)

(my answer needs to be more than 30 characters!)

like image 181
Ben Bolker Avatar answered Sep 27 '22 19:09

Ben Bolker