Search code examples
rcsvfor-looplinear-regressionplyr

In R how to loop through csv files and safe outputs of linear regression in new dataframe?


My script and one of the first 3 csv files are can be found in my Github folder

I have split a list of NDVI and climate data into small csv. files with 34 years of data each.

Every 34 years should then be split into two parts depending on a conflict year, saved in the same table and a certain time range. But this part of the code works already.

Now I want to control the second part of the list with the climate data of the first part, by using multiple linear regression, which is also done.

I basically need to make a loop to store all the coefficients from every round of the lm function of one csv. file in a new list.

I know that I can use lapply to loop and get the output as a list. But there are some missing parts to actually loop through the csv. files.

#load libraries
library(ggplot2)
library(readr)
library(tidyr)
library(dplyr)
library(ggpubr)
library(plyr)
library(tidyverse)
library(fs)


file_paths <- fs::dir_ls("E:\\PYTHON_ST\\breakCSV_PYTHON\\AIM_2_regions\\Afghanistan")
file_paths

#create empty list and fill with file paths and loop through them
file_contents <- list()
for (i in seq_along(file_paths)) { #seq_along for vectors (list of file paths is a vector)
  file_contents[[i]] <- read_csv(file = file_paths[[i]])
                  
                for (i in seq_len(file_contents[[i]])){ # redundant?
                  
                 # do all the following steps in every file                                        
                 
                 # Step 1) 
                 # Define years to divide table
                 
                 #select conflict year in df 
                 ConflictYear = file_contents[[i]][1,9]
                 ConflictYear
                 
                 # select Start year of regression in df
                 SlopeYears = file_contents[[i]][1,7] #to get slope years (e.g.17)
                 BCStartYear = ConflictYear-SlopeYears #to get start year for regression
                 BCStartYear
                 
                 #End year of regression
                 ACEndYear = ConflictYear+(SlopeYears-1) # -1 because the conflict year is included
                 ACEndYear
                 
                 
                 # Step 2
                 
                 #select needed rows from df
                 #no headers but row numbers. NDVI.Year = [r1-r34,c2]
                 NDVI.Year <- file_contents[[i]][1:34,2]
                 NDVI <- file_contents[[i]][1:34,21]
                 T.annual.max <- file_contents[[i]][1:34,19]
                 Prec.annual.max <- file_contents[[i]][1:34,20]
                 soilM.annual.max <- file_contents[[i]][1:34,18]
                 
                 #Define BeforeConf and AfterConf depending on Slope Year number and Conflict Years
                 #Go through NDVI.Year till Conflict.Year (-1 year) since the conflict year is not included in bc
                 BeforeConf1 <- file_contents[[i]][ which(file_contents[[i]]$NDVI.Year >= BCStartYear & file_contents[[i]]$NDVI.Year < ConflictYear),] #eg. 1982 to 1999
                 BeforeConf2 <-  c(NDVI.Year, NDVI, T.annual.max, Prec.annual.max, soilM.annual.max) #which columns to include
                 BeforeConf <- BeforeConf1[BeforeConf2] #create table
                 
                 AfterConf1 <- myFiles[ which(file_contents[[i]]$NDVI.Year >= ConflictYear & file_contents[[i]]$NDVI.Year <= ACEndYear),] #eg. 1999 to 2015
                 AfterConf2 <-  c(NDVI.Year, NDVI, T.annual.max, Prec.annual.max, soilM.annual.max)
                 AfterConf <- AfterConf1[AfterConf2]
                 
                 #Step 3)a)
                 #create empty list, to fill with coefficient results from each model results for each csv file and safe in new list
                 
                 #Create an empty df for the output coefficients
                 names <- c("(Intercept)","BeforeConf$T.annual.max","BeforeConf$Prec.annual.max","BeforeConf$soilM.annual.max")
                 coef_df <- data.frame()
                 for (k in names) coef_df[[k]] <- as.character() 
                 
                 #Apply Multiple Linear Regression
                 plyrFunc <- function(x){
                   model <- lm(NDVI ~ T.annual.max + Prec.annual.max + soilM.annual.max, data = BeforeConf)
                   return(summary(model)$coefficients[1,1:4])
                 }
                 
                 coef_df <- ddply(BeforeConf, .(), x)
                 coef_DF
    }}

Solution

  • Since you have code working for a single CSV, consider separating process and loop. Specifically:

    1. Create a function that receives a single csv path as input parameter and does everything you need for a single file.

      get_coeffs <- function(csv_path) {
        df <- read.csv(csv_path)
      
        ### Step 1
        # select conflict year, start year, and end year in df 
        ConflictYear <- df[1,9]
        SlopeYears <- df[1,7]                       # to get slope years (e.g.17)
        BCStartYear <- ConflictYear - SlopeYears    # to get start year for regression
        ACEndYear <- ConflictYear + (SlopeYears-1)  # -1 because the conflict year is included
      
        ### Step 2
        # select needed rows from df
        #no headers but row numbers. NDVI.Year = [r1-r34,c2]
        NDVI.Year <- df[1:34, 2]
        NDVI <- df[1:34, 21]
        T.annual.max <- df[1:34, 19]
        Prec.annual.max <- df[1:34, 20]
        soilM.annual.max <- df[1:34, 18]
      
        # Define BeforeConf and AfterConf depending on Slope Year number and Conflict Years
        # Go through NDVI.Year till Conflict.Year (-1 year) since the conflict year is not included in bc
        BeforeConf1 <- df[ which(df$NDVI.Year >= BCStartYear & df$NDVI.Year < ConflictYear),]
        BeforeConf2 <- c(NDVI.Year, NDVI, T.annual.max, Prec.annual.max, soilM.annual.max)
        BeforeConf  <- BeforeConf1[BeforeConf2] #create table
      
        AfterConf1 <- myFiles[ which(df$NDVI.Year >= ConflictYear & df$NDVI.Year <= ACEndYear),]
        AfterConf2 <- c(NDVI.Year, NDVI, T.annual.max, Prec.annual.max, soilM.annual.max)
        AfterConf  <- AfterConf1[AfterConf2]
      
        ### Step 3
        tryCatch({
            # Run model and return coefficients
            model <- lm(NDVI ~ T.annual.max + Prec.annual.max + soilM.annual.max, data = BeforeConf) 
            return(summary(model)$coefficients[1,1:4])
        }, error = function(e) {
            print(e)
            return(rep(NA, 4))
        })
      }
      
    2. Loop through csv paths, passing each file into your function, building a list of results which you can handle with lapply for list return or sapply (or vapply that specifies length and type) for simplified return such as vector, matrix/array if applicable.

      mypath <- "E:\\PYTHON_ST\\breakCSV_PYTHON\\AIM_2_regions\\Afghanistan"
      file_paths <- list.files(pattern=".csv", path=mypath)
      
      # LIST RETURN
      result_list <- lapply(file_paths, get_coeffs)
      
      # MATRIX RETURN
      results_matrix <- sapply(file_paths, get_coeffs)
      results_matrix <- vapply(file_paths, get_coeffs, numeric(4))