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

后端 未结 2 582
暖寄归人
暖寄归人 2020-12-30 18:21

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


        
相关标签:
2条回答
  • 2020-12-30 18:41

    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
    
    0 讨论(0)
  • 2020-12-30 18:56

    Simple, just do this:

    as.list(c(1,2,3))
    
    0 讨论(0)
提交回复
热议问题