user3763919
user3763919

Reputation: 13

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. 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 <- 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!

Upvotes: 1

Views: 834

Answers (1)

MrFlick
MrFlick

Reputation: 206526

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).

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

Upvotes: 3

Related Questions