将向量转换为列表,将向量中的每个元素作为列表中的元素

矢量是这样的:

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

我需要这样的东西:

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

我试过了:

list(c(1,2,3))
#[[1]]
#[1] 1 2 3
88933 次浏览

Simple, just do this:

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

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