Convert a vector into a list, each element in the vector as an element in the list

RR Faq

R Problem Overview


The vector is like this:

c(1,2,3)
#[1] 1 2 3

I need something like this:

list(1,2,3)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] 3

I tried this:

list(c(1,2,3))
#[[1]]
#[1] 1 2 3

R Solutions


Solution 1 - R

Simple, just do this:

as.list(c(1,2,3))

Solution 2 - R

An addition to the accepted answer: if you want to add a vector to other elements in a longer list, as.list() may not produce what you expect. For example: you want to add 2 text elements and a vector of five numeric elements (1:5), to make a list that is 7 elements long.

L<-list("a","b",as.list(1:5)) 

Oops: it returns a list with 3 elements, and the third element has a sub-list of 5 elements; not what we wanted! The solution is to join two separate lists:

L1<-list("a","b")
L2<-as.list(1:5)
L<-c(L1,L2) #7 elements, as expected

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionqedView Question on Stackoverflow
Solution 1 - RqedView Answer on Stackoverflow
Solution 2 - RJohnView Answer on Stackoverflow