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 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))