Generate an incrementally increasing sequence like 112123123412345
Asked Answered
S

4

9

Basically I want to generate a sequence, say:

n is 2, the sequence will be 112
n is 3, sequence is 112123
n is 5, sequence is 112123123412345

I did come up with a solution

n=5
seq=1
for (i in 2:n){
  seq=c(seq,rep(1:n,len=i))
}

I am wondering if there is a way can do it without for loop?

Surfing answered 11/10, 2013 at 11:33 Comment(0)
E
20

Use sequence:

> sequence(1:5)
 [1] 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Ecliptic answered 11/10, 2013 at 11:37 Comment(3)
There is also something somewhat satisfying in doing sequence(sequence(5)) :-)Bookkeeper
@Chris: make sure to read the "See Also" sections of the help files. ?seq mentions sequence there.Ecliptic
@JoshuaUlrich Thanks man, I guess I really need to build the habit of reading help page properly, I did go there but ignored everything except arguments and examples.Surfing
H
7

Here is one possibility:

n<-5
unlist(lapply(1:n,function(x) 1:x))
## [1] 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Him answered 11/10, 2013 at 11:36 Comment(4)
more functional, would be unlist(lapply(seq(n),seq))Bookkeeper
+1, since sequence is defined as function (nvec) unlist(lapply(nvec, seq_len)).Ecliptic
Thanks a lot guys! Though this question can be solved by sequence(), it is actually a question from my tutorial practice, asking how to do something using lapply() instead of loop, I think this is what the tutorial question is looking for.Surfing
if you look at the sequence code you will see how similar are the responses.Exoenzyme
P
5

It'd do something like:

do.call('c', sapply(1:5, seq, from = 1))
# [1] 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Pascasia answered 11/10, 2013 at 11:38 Comment(0)
M
1

I misread the question as "how to generate that annoying puzzler sequence," which goes 1,11,21,1112,3112,... :-). So I figured I might as well write a solution to that.

puzseq<-function(seqlen) {
theseq<- list(1)
for( j in 2:seqlen) {

thetab<-table(theseq[[j-1]])
theseq[[j]]<-unlist( sapply( 1:length(thetab), function(k) c(thetab[k], as.numeric(names(thetab)[k])) ))
}
return(theseq)
}
Municipality answered 11/10, 2013 at 13:17 Comment(2)
This is difficult to read; code formatting is not standard and not consistent.Snapback
@ClaytonStanley could you clarify what you find unclear? It better be more than lack of indents for loop contents!Municipality

© 2022 - 2024 — McMap. All rights reserved.