Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert named vector to list in R

Tags:

r

vector

Suppose I have the following named numeric vector:

a <- 1:8
names(a) <- rep(c('I', 'II'), each = 4)

How can I convert this vector to a list of length 2 (shown below)?

a.list
# $I
# [1] 1 2 3 4
# $II
# [1] 5 6 7 8

Note that as.list(a) is not what I'm looking for. My very unsatisfying (and slow for large vectors) solution is:

names.uniq <- unique(names(a))
a.list <- setNames(vector('list', length(names.uniq)), names.uniq)
for(i in 1:length(names.uniq)) {
  names.i <- names.uniq[i]
  a.i <- a[names(a)==names.i]
  a.list[[names.i]] <- unname(a.i)
}

Thank you in advance for your help, Devin

like image 392
Devin King Avatar asked Sep 16 '17 08:09

Devin King


People also ask

How do I create a list vector in R?

Converting a List to Vector in R Language – unlist() Function. unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.

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

For example, if we have a vector x then it can be converted to data frame by using as. data. frame(x) and this can be done for a matrix as well.

How do I remove a name from a vector in R?

To assign names to the values of vector, we can use names function and the removal of names can be done by using unname function. For example, if we have a vector x that has elements with names and we want to remove the names of those elements then we can use the command unname(x).

How do I convert a list to a character 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.


1 Answers

Like I said in the comment, you can use split to create a list.

a.list <- split(a, names(a))
a.list <- lapply(a.list, unname)

A one-liner would be

a.list <- lapply(split(a, names(a)), unname)
#$I
#[1] 1 2 3 4
#
#$II
#[1] 5 6 7 8

EDIT.
Then, thelatemail posted a simplification of this in his comment. I've timed it using Devin King's way and it's not only simpler it's also 25% faster.

a.list <- split(unname(a),names(a))
like image 158
Rui Barradas Avatar answered Oct 14 '22 03:10

Rui Barradas