如何在R中按顺序获得下一个数字 [英] How to get next number in sequence in R

查看:82
本文介绍了如何在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


  1. 数字的向量(例如3,7,13,21)

  2. 接下来的数字是多少

  1. a vector of numbers(3,7,13,21 e.g.)
  2. 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 



推荐答案

通过数学的力量!

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 

作为函数:

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






在模式可能为 n 订单较深,例如:

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

这篇关于如何在R中按顺序获得下一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆