2

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

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

提前致谢,

加布里埃尔。

4

3 回答 3

4

你可以做:

lapply(seq_along(my.vector), head, x = my.vector)
于 2015-12-16T15:30:38.560 回答
3

我们可以用

v1 <- my.vector[sequence(seq_along(my.vector))]
split(v1, cumsum(v1=='a'))
于 2015-12-16T15:22:27.267 回答
3

这是一种方法(比@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"
## 

如果您想要 amatrix而不是 a 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" 
于 2015-12-16T15:27:20.400 回答