简体   繁体   English

如何创建函数以找到两个向量的索引斜率

[英]How to create a function the finds the indexed slope of two vectors

I have looked everywhere for this answer but I am having a hard time even figuring our how to ask this question. 我到处都在寻找这个答案,但是我很难弄清楚我们如何问这个问题。 I am trying to create a function such that it creates a vector that is a function of two other vectors, where I use a for loop to index values at k and k+1. 我试图创建一个函数,使其创建一个向量,该向量是另外两个向量的函数,在这里我使用了for循环来索引k和k + 1处的值。 Here is an example of my code, which does not work: 这是我的代码的示例,该示例不起作用:

x <- 1:10
y <- x^2

d <- data.frame(x,y)

invSlope <- NULL

invSlope.f <- function(X,Y){
    for(k in 1:length(X)-1){
        invSlope[k] = (X[k+1] - X[k])/ (Y[k+1] - Y[k])
        invSlope[length(X)] = 0
        return(invSlope)
    }
}

d$invSlope <- invSlope.f(d$x,d$y)

What I am trying to accomplish is at d$invSlope[1] I have the inverse of the slope of the line that comes after it (delta x/delta y). 我想要完成的是在d $ invSlope [1]处,其后的线的斜率(delta x / delta y)与之成反比。 The last value of the vector would just be 0. I can accomplish this with a for loop (or even nested for loops), but I would like to generalize this to a function. 向量的最后一个值将是0。我可以通过for循环(甚至嵌套为for循环)来完成此操作,但是我想将其概括为一个函数。

Thanks 谢谢

diff函数是一种矢量化方法...我们不需要“ steenkin”循环:

finvslope <- function(xseq, yseq) { c( diff(xseq)/diff(yseq) , 0) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM