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
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.
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.
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).
To convert List to Vector in R, use the unlist() function. The unlist() function simplifies to produce a vector by preserving all atomic components.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With