R - Generate a sequence of numbers

折月煮酒 提交于 2019-11-28 11:56:59

I find the sequence function to be helpful in this case. If you had your data in a structure like this:

(info <- data.frame(start=c(1, 144, 288), len=c(6, 6, 6)))
#   start len
# 1     1   6
# 2   144   6
# 3   288   6

then you could do this in one line with:

sequence(info$len) + rep(info$start-1, info$len)
#  [1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293

Note that this solution works even if the sequences you're combining are different lengths.

Here's one approach:

unlist(lapply(c(0L,(1:2)*144L-1L),`+`,seq_len(6)))
# or...
unlist(lapply(c(1L,(1:2)*144L),function(x)seq(x,x+5)))

Here's a way I like a little better:

rep(c(0L,(1:2)*144L-1L),each=6) + seq_len(6)

Generalizing...

rlen  <- 6L
rgap  <- 144L
rnum  <- 3L

starters <- c(0L,seq_len(rnum-1L)*rgap-1L)

rep(starters, each=rlen) + seq_len(rlen)
# or...
unlist(lapply(starters+1L,function(x)seq(x,x+rlen-1L)))

This can also be done using seq or seq.int

x = c(1, 144, 288)
c(sapply(x, function(y) seq.int(y, length.out = 6)))

#[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293

As @Frank mentioned in the comments here is another way to achieve this using @josilber's data structure (This is useful particularly when there is a need of different sequence length for different intervals)

c(with(info, mapply(seq.int, start, length.out=len)))

#[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293

I am using R 3.3.2. OSX 10.9.4

I tried:

a<-c()  # stores expected sequence
f<-288  # starting number of final sub-sequence
it<-144 # interval
for (d in seq(0,f,by=it))
{
    if (d==0)
    {
        d=1
    }
    a<-c(a, seq(d,d+5))
    print(d)
}
print(a)

AND the expected sequence stores in a.

[1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293

And another try:

a<-c()  # stores expected sequence
it<-144 # interval
lo<-4   # number of sub-sequences
for (d in seq(0,by=it, length.out = lo))
{
    if (d==0)
    {
        d=1
    }
    a<-c(a, seq(d,d+5))
    print(d)
}
print(a)

The result:

[1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293 432 433 434 435 436 437

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!