0

I want to run a function called autocorrelation over several data frames. Also, I want to save the values of the structure called Ac_results I get every time I run the function. Therefore, it is like I want to concatenate the values one below another every time the function runs. Currently, I create a data frame outside the function and try to update it inside the function concatenating the new values using the function cbind, but it is not working. Any idea about how to solve it?

Ac <- data.frame("Name"=character(),"Lag1"=double(),"Low"=double(),"Up"=double(),"Significance"=character())

#AUTOCORRELATION
autocorrelation <- function(x,y,i){
  mean_x <- mean(x)
  Denominador <- (x[] - mean(x))^2 #Denominator 
  k=1; n=length(x)-k; u=1
  Numerador <- numeric(n)
  for (u in 1:n) {
    Numerador[u] <- (x[u] - mean_x)*(x[u+k] - mean_x) #Numerador
  }
  Lag1 <- ifelse(sum(Denominador)!=0,((1/(length(x)-1))*sum(Numerador))/((1/length(x))*sum(Denominador)),0) #Lag 1
  low <- (-1 - (1.96*sqrt(length(x)-2)))/(length(x)-1) #5% significance level
  up <- (-1 + (1.96*sqrt(length(x)-2)))/(length(x)-1) #5% significance level
  Significance <- ifelse( up <= Lag1 & Lag1 >= low,"Independent","No independent") #Significance
  Ac_results <- structure(list(Name=y,Lag1=Lag1,Low=low,Up=up,Significance=Significance)) #save the results
  Ac <- cbind(Ac, Ac_results)
}

write.csv(Ac, file ="Lag.csv")
Sss
  • 427
  • 2
  • 8
  • Functions should not modify variables outside their scope. The function should return an updated value that you can save later. – MrFlick Apr 20 '21 at 17:17
  • Could you provide a simple sample about how to do that? – Sss Apr 20 '21 at 17:19
  • This existing question pretty much sums it up: https://stackoverflow.com/questions/3969852/update-data-frame-via-function-doesnt-work – MrFlick Apr 20 '21 at 17:22

0 Answers0