Jasmeen Bong
Jasmeen Bong

Reputation: 67

How to shorten notation for vector

I would like to create a vector and here is my code:

x <- c(-1071, -1072, -1073, -1074, -1075, -1074, -1073, -1072, -1071)

May I know how to do it in a shortened notation?

Upvotes: 0

Views: 210

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270020

Assuming that we want a declining sequence with initial step size -1 that reverses half way and that the inputs are the sequence length, n, and the first element, a, we have:

n <- 9 # number of elements
a <- -1071 # first element

p <- seq(a, length = n, by = -1)
pmax(p, rev(p))
## [1] -1071 -1072 -1073 -1074 -1075 -1074 -1073 -1072 -1071

If the inputs are the maximum and minimum elements where the first element is the maximum then:

a <- -1071 # max / first
b <- -1075 # min

c(a:b, (b:a)[-1])
## [1] -1071 -1072 -1073 -1074 -1075 -1074 -1073 -1072 -1071

Upvotes: 1

Related Questions