Search code examples
rloopscsvimport-from-excel

Creating a Loop Function with read_csv - RStudio


I have code in RStudio which imports a csv based on criteria by using paste function.

Name <- "Sam"
Location <- "Barnsley"
Code <- "A"

Test2 <- read_csv(paste("C:/Users/....,Opposition , " (",Code,")/Vs ",Location, " (",Code,") Export for ",Name,".csv",sep = ""),skip = 8)

I usually follow this import code by a few lines of code for calculations. For arguments sake: Run Code Series

I would like to recreate this code in order to create a list of names, and have the code run through each 1 by 1 followed by running the code.

Desired:

Name <- c("Sam","David","Paul","John")

Then be able to run the import code and have it Run Code Series after each import before importing the next name.


Solution

  • I believe from your question that you want to end with a separate dataframe for each name. If so, you could do it like this:

    Names <- c("Sam","David","Paul","John")
    Location <- "Barnsley"
    Code <- "A"
    for(i in Names){
        Test2 <- read_csv(paste("C:/Users/....,Opposition" , " (", Code,")/Vs ", Location, " (",Code,") Export for ", i, ".csv", sep = ""), skip = 8)
        Run Code Series
        assign(paste("df_for_", i, sep = ""), Test2)
    }
    

    This will go through your list of names and within the loop, open the file as Test2. You perform your calculations on Test2, and then assign it to a dataframe for the particular name in the list using paste. Also your quotes in your read_csv line do not match up, so that will need to be corrected.