R:从 "triangular" 形式的向量创建列表

R: Create list from vector in "triangular" form

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

> 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'))

这是一种方法(比@akrun 的方法更冗长,但不依赖于原始向量中的实际值)。

split(my.vector[sequence(seq_along(my.vector))], 
      rep(seq_along(my.vector), seq_along(my.vector)))
## $`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"
## 

如果您想要 matrix 而不是 list,您可以尝试:

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

你可以这样做:

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