Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:从“中的向量”创建列表;三角形“;形式_R_List_Vector_Triangular - Fatal编程技术网

R:从“中的向量”创建列表;三角形“;形式

R:从“中的向量”创建列表;三角形“;形式,r,list,vector,triangular,R,List,Vector,Triangular,我发现很难表述这个问题,但我想找到一种聪明的方法(不使用循环)来获得以下结果: > my.vector = letters[1:6] > print(my.vector) [1] "a" "b" "c" "d" "e" "f" > > my.list = (rep(list(NA),6)) > for (i in 1:length(my.vector)){ + x = my.vector[1:i] + my.list[[i]] = x + } > p

我发现很难表述这个问题,但我想找到一种聪明的方法(不使用循环)来获得以下结果:

> my.vector = letters[1:6]
> print(my.vector)
[1] "a" "b" "c" "d" "e" "f"
> 
> my.list = (rep(list(NA),6))
> for (i in 1:length(my.vector)){
+   x = my.vector[1:i]
+   my.list[[i]] = x
+ }
> print(my.list)
[[1]]
[1] "a"

[[2]]
[1] "a" "b"

[[3]]
[1] "a" "b" "c"

[[4]]
[1] "a" "b" "c" "d"

[[5]]
[1] "a" "b" "c" "d" "e"

[[6]]
[1] "a" "b" "c" "d" "e" "f"
提前感谢,

加布里埃尔。

我们可以使用

v1 <- my.vector[sequence(seq_along(my.vector))]
split(v1, cumsum(v1=='a'))
v1这里有一种方法(比@akrun更详细,但不依赖于原始向量中的实际值)


如果您想要一个
矩阵
而不是
列表
,您可以尝试:

> x <- t(replicate(length(my.vector), my.vector))
> x[upper.tri(x)] <- ""
> x
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a"  ""   ""   ""   ""   ""  
[2,] "a"  "b"  ""   ""   ""   ""  
[3,] "a"  "b"  "c"  ""   ""   ""  
[4,] "a"  "b"  "c"  "d"  ""   ""  
[5,] "a"  "b"  "c"  "d"  "e"  ""  
[6,] "a"  "b"  "c"  "d"  "e"  "f" 
>x x[上三(x)]x
[,1] [,2] [,3] [,4] [,5] [,6]
[1,]“a”“”“”
[2,]a“b”
[3]“a”“b”“c”
[4,]a“b”c“d”
[5,]a“b”c“d”e
[6,]“a”“b”“c”“d”“e”“f”
您可以执行以下操作:

lapply(seq_along(my.vector), head, x = my.vector)
lapply(seq_along(my.vector), head, x = my.vector)