Save results using function in R

Viewed 100

I am trying to run a function called autocorrelation that I have created in R and I want to run it over all the data frames that I have saved in a list

This is my current code

autocorrelation <- function(x,y){
  mean_x <- mean(x)
  Denominador <- (x[] - mean(x))^2 #Denominator 
  k=1; n=length(x)-k; u=1
  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
  Autocorrelation_results <- structure(list(Name=y,Lag1=Lag1,Low=low,Up=up,Significance=Significance)) #save the results
}

for (i in seq_along(listDF_Ann)){
  x<- listDF_Ann[[i]]$Qmean
  y <- names(listDF)[i]
  autocorrelation(x,y)
}
  

and this is my input

> dput(listDF_Ann[[1]]$Qmean)
c(80.74, 64.152602739726, 68.7273224043716, 132.860273972603, 
337.284931506849, 78.3835616438356, 204.416120218579, 58.7824657534247, 
315.110684931507, 146.238356164384, 127.573770491803, 286.835616438356, 
353.802739726027, 88.3093150684931, 304.866666666667, 172.287123287671, 
90.4186301369863, 51.1808219178082, 131.634153005464, 608.193150684932, 
49.1172602739726, 257.268493150685, 112.969945355191, 50.0246575342466, 
275.166849315068, 548.178082191781, 405.07650273224, 97.0849315068493, 
202.31095890411, 452.841095890411, 206.071038251366, 518.246575342466, 
182.787945205479, 309.183561643836, 233.625683060109, 83.5260273972603, 
51.4739726027397, 340.13698630137, 308.68306010929, 616.715068493151, 
107.912328767123, 342.956164383562, 37.9808743169399, 151.323287671233, 
231.164383561644, 90.786301369863, 38.0136612021858, 185.421917808219, 
38.0167123287671, 142.664109589041, 114.443442622951, 281.054246575342, 
92.0813698630137, 96.5923287671233, 289.146721311475, 149.043287671233, 
251.462739726027, 54.4093150684932, 81.118306010929, 168.744931506849, 
73.9879452054794, 124.941917808219, 151.301366120219, 258.280547945205, 
29.5304109589041, 263.763561643836, 218.915027322404)

The current code works, but I do not know how to save the results (structure?) for each data frame x when I run the function. After I want to export the results for all x. Any idea?

1 Answers

You could go with write.csv, dplyr's write_tsv(Autocorrelation_results, filename), or something along the line.

Pass i into the loop, so you can generate a filename with paste

autocorrelation <- function(x,y,i){
    [...]
    filename <- paste0("outfile_", i, ".tsv)
    write_tsv(Autocorrelation_results, filename)
}
Related