Q:

How to get next number in sequence in R

I need to automate the process of getting the next number(s) in the given sequence.
Can we make a function which takes two inputs 

a vector of numbers(3,7,13,21 e.g.)
how many next numbers
seqNext <- function(sequ, next) {
..
}

seqNext( c(3,7,13,21), 3) 
# 31 43 57
seqNext( c(37,26,17,10), 1)
# 5 

A:

By the power of maths!
x1 <- c(3,7,13,21)
dat <- data.frame(x=seq_along(x1), y=x1)

predict(lm(y ~ poly(x, 2), data=dat), newdata=list(x=5:15))
#  1   2   3   4   5   6   7   8   9  10  11 
# 31  43  57  73  91 111 133 157 183 211 241 

When dealing with successive differences that change their sign, the pattern of output values ends up switching from decreasing to increasing:
x2 <- c(37,26,17,10)

dat <- data.frame(x=seq_along(x2), y=x2)
predict(lm(y ~ poly(x,2), data=dat), newdata=list(x=1:10))

# 1      2      3      4      5      6      7      8      9     10 
#37     26     17     10      5      2      1      2      5     10
   -(11)   -(9)   -(7)    -(5)   -(3)   -(1)  -(-1)  -(-3) -(-5)
        -2     -2      -2     -2     -2    -2     -2     -2 

As a function:
seqNext <- function(x,n) {
  L <- length(x)
  dat <- data.frame(x=seq_along(x), y=x)
  unname(
    predict(lm(y ~ poly(x, 2), data=dat), newdata=list(x=seq(L+1,L+n)))
  )
}

seqNext(x1,5)
#[1] 31 43 57 73 91
seqNext(x2,5)
#[1] 5 2 1 2 5

This is also easily extensible to circumstances where the pattern might be n orders deep, e.g.:
x3 <- c(100, 75, 45, 5, -50)
diff(x3)
#[1] -25 -30 -40 -55
diff(diff(x3))
#[1]  -5 -10 -15
diff(diff(diff(x3)))
#[1] -5 -5

seqNext <- function(x,n,degree=2) {
  L <- length(x)
  dat <- data.frame(x=seq_along(x), y=x)
  unname(
    predict(lm(y ~ poly(x, degree), data=dat), newdata=list(x=seq(L+1,L+n)))
  )
}

seqNext(x3,n=5,deg=3)
#[1] -125 -225 -355 -520 -725

