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
2 个解决方案
#1
81
Simple, just do this:
很简单,就这样做:
as.list(c(1,2,3))
#2
1
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.
对已接受答案的补充:如果要将向量添加到较长列表中的其他元素,as.list()可能无法生成您期望的内容。例如:您要添加2个文本元素和一个包含五个数字元素(1:5)的向量,以生成长度为7个元素的列表。
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:
糟糕:它返回一个包含3个元素的列表,第三个元素有一个包含5个元素的子列表;不是我们想要的!解决方案是加入两个单独的列表:
L1<-list("a","b")
L2<-as.list(1:5)
L<-c(L1,L2) #7 elements, as expected
#1
81
Simple, just do this:
很简单,就这样做:
as.list(c(1,2,3))
#2
1
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.
对已接受答案的补充:如果要将向量添加到较长列表中的其他元素,as.list()可能无法生成您期望的内容。例如:您要添加2个文本元素和一个包含五个数字元素(1:5)的向量,以生成长度为7个元素的列表。
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:
糟糕:它返回一个包含3个元素的列表,第三个元素有一个包含5个元素的子列表;不是我们想要的!解决方案是加入两个单独的列表:
L1<-list("a","b")
L2<-as.list(1:5)
L<-c(L1,L2) #7 elements, as expected