Home > Software design >  How can I import .cvs files with a loop in R?
How can I import .cvs files with a loop in R?

Time:09-30

I've got a series of .cvs files called Natalidad[i], where [i] is the year of the data from 1996 to 2020. I want to make I loop in order to load each of them. I've tried the next code, but it is working.

for (i in 1996:2020) { 
  nacimientos[i] <- read.csv("Natalidad [i]_p.csv", header = TRUE, sep = ";") 
}

I've also tried without [] and substituting with (). My question might be basic. I'm not familiarized with loops in R, so there's probably something essential that I'm missing.

CodePudding user response:

As you originally tagged the question as Python, it could be done as follows:

import pandas as pd

nacimientos = [pd.read_csv(f"Natalidad [{year}]_p.csv", sep=";") for year in range(1996, 2021)]

This creates a list of dataframes with the first being for 1996. It uses a Python "list comprehension" to build the list.

This would be equivalent to:

nacimientos = []

for year in range(1996, 2021):
    df = pd.read_csv(f"Natalidad [{year}]_p.csv", sep=";")
    nacimientos.append(df)

CodePudding user response:

If you do this in R, you have to paste the string of the file name first. R cannot have variables inside a string. E.g. paste0("first part", i, "second part"), where i is the variable.

Try

for (i in 1996:2020) { 
  nacimientos[i] <- read.csv(paste0("Natalidad ", [i], "_p.csv"), header = TRUE, sep = ";") 
}
  • Related