简体   繁体   English

在循环中迭代计算线性回归

[英]Calculating linear regression with iteration in a loop

I'm working in R and I have 2 vectors, LE and NEE (of lengths 5265) with which I would like to calculate the linear regression between the two, but for 5 points at a time and put each 5 point regression coefficient value into another vector called WUE_5. 我在R工作,我有2个向量,LE和NEE(长度为5265),我想用它计算两者之间的线性回归,但是一次得到5个点,并将每个5点回归系数值放入另一个名为WUE_5的向量。 This is the function I have for calculating the regression coefficient for all of the points: 这是我计算所有点的回归系数的函数:

WUE_function <- function(NEE, LE) {
  return(lm(NEE ~ LE)$coefficients[2])
}

I can't figure out how to write a loop that would essentially consist of 我无法弄清楚如何编写一个基本上由以下组成的循环

WUE_5 <- c(lm(NEE[1:5] ~ LE[1:5])$coefficients[2],
           lm(NEE[2:6] ~ LE[2:6])$coefficients[2],
           ..., etc)

I tried this with some arbitrary vectors x and y but this is the result: 我尝试了一些任意向量x和y,但这是结果:

x <- c(1:10)
y <- c(2, 5, 3, 6, 7, 8, 13, 6, 3, 8)
n <- 7
i <- 1
z <- NULL


while(i < n){
  z[i] <- lm(x[i:i+4] ~ y[i:i+4])$coefficients[2]
  i <- i+1 
} 

z
# [1] NA NA NA NA NA NA 

I don't understand what I'm doing wrong that's making z filled with NA's Thank you in advance for the help! 我不明白我做错了什么让z充满NA的感谢你提前感谢你的帮助!

The sequence operator : has high precedence then the addition operator + . 序列运算符:具有高优先级,然后是加法运算符+ This means that i:i+4 translates to i+4 (which is a single element). 这意味着i:i+4转换为i+4 (这是单个元素)。

If you did 如果你这样做了

z[i]<- lm(x[i:(i+4)]~y[i:(i+4)])$coefficients[2]

instead, I believe you will get the result you are after 相反,我相信你会得到你所追求的结果

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

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