How to do sequence in R?

Asked

Viewed 1,241 times

3

I need to do this sequence in a repeating structure to use with a larger N, but I’m not getting it done, does anyone have any idea how to do this?

n=8
names <- c (seq(1 , n), seq(2,n+1 ), seq (3,n+2), seq(4 ,n+3), seq(5,n+5 ),seq(6,n+5),seq(7, n+6 ), seq (8,n+7))

Thanks in advance..

  • 3

    I think your code is wrong, wouldn’t it seq(5,n+4)? It makes more sense by the logic of the other sequences.

2 answers

3


If what you want is a way to make the sequence more dynamic, you can use the following:

n=8
names <- rep(1:n, n)+rep(0:(n-1), each=n)
#[1]  1  2  3  4  5  6  7  8  2  3  4  5  6  7  8  9  3  4  5  6  7  8
#[23]  9 10  4  5  6  7  8  9 10 11  5  6  7  8  9 10 11 12  6  7  8  9
#[45] 10 11 12 13  7  8  9 10 11 12 13 14  8  9 10 11 12 13 14 15

That way you create the sequence 1:n n times, and adds 0, 1, 2...n-1 each 1:n.

  • That’s what I was looking for, thank you very much :)

1

Complementing with one more response option, you can also use lapply.

criar_seq <- function(x){
    seq(x, (n+x-1))
}

n <- 8
lapply(1:n, criar_seq)

This will return a list of n sequences with the progression of one more. If you want to put the data as vector, just apply unlist.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.