[英]How to create a sequence of sequences of numbers in R?
I would like to make the following sequence in R, by using rep
or any other function.我想通过使用
rep
或任何其他 function 在 R 中进行以下序列。
[1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5]
Basically, c(1:5, 2:5, 3:5, 4:5, 5:5)
.基本上,
c(1:5, 2:5, 3:5, 4:5, 5:5)
。
Use sequence
.使用
sequence
。
sequence(5:1, from = 1:5)
[1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
The first argument, nvec
, is the length of each sequence ( 5:1
);第一个参数
nvec
是每个序列的长度 ( 5:1
); the second, from
, is the starting point for each sequence ( 1:5
).第二个,
from
,是每个序列的起点( 1:5
)。
Note : this works only for R >= 4.0.0.注意:这仅适用于 R >= 4.0.0。 From R News 4.0.0 :
来自R 新闻 4.0.0 :
sequence()
[...] gains arguments [egfrom
] to generate more complex sequences.sequence()
[...] 获得 arguments [例如from
] 以生成更复杂的序列。
unlist(lapply(1:5, function(i) i:5))
# [1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
Your mention of rep
reminded me of replicate
, so here's a very stateful solution.你提到
rep
让我想起了replicate
,所以这是一个非常有状态的解决方案。 I'm presenting this because it's short and unusual, not because it's good.我提出这个是因为它简短且不寻常,而不是因为它很好。 This is very unidiomatic R.
这是非常通用的 R。
vect <- 0:5
unlist(replicate(5, vect <<- vect[-1]))
[1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
You can do it with a combination of rep
and lapply
, but it's basically the same as Merijn van Tilborg's answer.您可以结合使用
rep
和lapply
,但这与 Merijn van Tilborg 的回答基本相同。
Here's an example of how not to do it:这是一个如何不这样做的示例:
out=c();for(i in 1:5){ out=c(out, (1:5)[i:5]) }
out
# [1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.