Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transform vector into list

Tags:

r

I have vector: c("A","1","2","3","B","4","5","D","6","7","8","9","10") I would like to transform this vector into list: list(A=c(1,2,3),B=c(4,5),...) Letters from vector are names in list of vectors. Vectors are from number blocks between letters.

like image 807
Wojciech Sobala Avatar asked Mar 02 '11 22:03

Wojciech Sobala


People also ask

Can you have a vector of lists?

A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.

How do I turn a vector into a list?

Convert Vector to List in R or create a list from vector can be done by using as. list() or list() functions. A Vector in R is a basic data structure consist elements of the same data type whereas an R List is an object consisting of heterogeneous elements meaning can contain elements of different types.

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

To convert Vector to List in R programming, use the as. list() function and pass the vector as a parameter, and it returns the list. The as. list() function convert objects to lists.

How do you add a vector to a list in C++?

Appending to a vector means adding one or more elements at the back of the vector. The C++ vector has member functions. The member functions that can be used for appending are: push_back(), insert() and emplace(). The official function to be used to append is push_back().


1 Answers

Here's one way. Nothing fancy, but it gets the job done.

x <- c("A","1","2","3","B","4","5","D","6","7","8","9","10")
y <- cumsum( grepl("[[:alpha:]]", x) )
z <- list()
for(i in unique(y)) z[[x[y==i][1]]] <- as.numeric(x[y==i][-1])
z
# $A
# [1] 1 2 3
#
# $B
# [1] 4 5
#
# $D
# [1]  6  7  8  9 10

# UPDATE: Trying to be a bit more "fancy"
a <- grepl("[[:alpha:]]", x)
b <- factor(cumsum(a), labels=x[a])
c <- lapply(split(x,b), function(x) as.numeric(x[-1]))
like image 119
Joshua Ulrich Avatar answered Oct 03 '22 03:10

Joshua Ulrich