Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a set of sequences with decreasing length in R

Tags:

r

sequence

I want to make a set of sequences from x to 20, with x = c(2:19). I want this, essentially, but without having to do it this way:

a = seq(2, 20)
b = seq(3, 20)
...
q = seq(18, 20)
r = seq(19, 20)

> a
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
> b
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
...
> q
[1] 18 19 20
> r
[1] 19 20`

I've attempted it using a for loop, but I can't get the replacement to work out:

a = c(2:20)
b = numeric()
for (i in 1:19){
b = seq(a[i]:20)
}

Any help?

like image 817
Nigel Stackhouse Avatar asked Dec 01 '22 21:12

Nigel Stackhouse


2 Answers

sapply(2:19, seq, to = 20)

[[1]]
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[2]]
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[3]]
 [1]  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[4]]
 [1]  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[5]]
 [1]  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[6]]
 [1]  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[7]]
 [1]  8  9 10 11 12 13 14 15 16 17 18 19 20

[[8]]
 [1]  9 10 11 12 13 14 15 16 17 18 19 20

[[9]]
 [1] 10 11 12 13 14 15 16 17 18 19 20

[[10]]
 [1] 11 12 13 14 15 16 17 18 19 20

[[11]]
[1] 12 13 14 15 16 17 18 19 20

[[12]]
[1] 13 14 15 16 17 18 19 20

[[13]]
[1] 14 15 16 17 18 19 20

[[14]]
[1] 15 16 17 18 19 20

[[15]]
[1] 16 17 18 19 20

[[16]]
[1] 17 18 19 20

[[17]]
[1] 18 19 20

[[18]]
[1] 19 20

If you want to save the object and give name to each element

res <- sapply(2:19, seq, to = 20)
names(res) <- letters[1:length(res)]
like image 79
dickoa Avatar answered Dec 19 '22 06:12

dickoa


Extending on dickoa's answer to assign global variables a to r (although I would not see why that would ever be preferable over storing in a list):

mapply(FUN=assign,x=letters[1:18],value=sapply(2:19, seq, to = 20),MoreArgs=list(envir=.GlobalEnv))

Gives:

> a
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
> b
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
> q
[1] 18 19 20
> r
[1] 19 20
like image 33
Sacha Epskamp Avatar answered Dec 19 '22 06:12

Sacha Epskamp