lacfo
lacfo

Reputation: 79

R iterate to read csv files

pollutantmean <- function(id){
    n <- length(id)
    for (i in 1 : n){
        pol <- read.csv('id[i].csv')
    }
}
pollutantmean(150:160)

The filenames of csv are like 001.csv, 002.csv, 100.csv etc 001, 002 and 100, these are id, and each csv has a column of id whose content is 1 if the filename is 001.

When I run this code, the console remind me this is no such file id[i].csv

Upvotes: 0

Views: 200

Answers (2)

lebatsnok
lebatsnok

Reputation: 6449

First of all, you don't need a loop. And second, you need to think about how to represent ids.

ids <- sprintf("%03i", 1:999) # 0's are padded at the beginning
filenames <- paste0(ids, ".csv")
results <- lapply(filenames, read.csv) # you get a list of data frames

Alternatively you can read in all csv files in a certain folder using, say:

results <- lapply(dir(pattern="\\.csv$"), read.csv)

The "\.csv$" stuff means that ".csv" has to be at the end of the filename. (see ?regexpr for technicalities)

... and a function that takes a number and gives you back a data frame would look like this:

read.this <- function(i) read.csv(sprintf("%003i.csv",i))

... And now you can lapply it to your desired range:

lapply(101:150, read.this)

Upvotes: 1

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7433

The first problem is line 4 and it should be replaced by

pol <- read.csv(paste0(id[i], ".csv"))

If id[i] is within quotes (either simple or double), it's understood litterally by read.csv, eg the function is looking for something named id[i].csv and which explains your error message.

But with such function, pol will be overwritten anyway at every step anyway.

If you really want to wrapup these lines into a function you need to return a list:

pollutantmean <- function(id){
    res <- vector("list", length(id))
    for (i in 1:n){
        res[[i]] <- read.csv(paste0(id[i], ".csv"))
    }
}

But a loop here would not be very elegant here, so we can simply:

pollutantmean <- function(id){
    lapply(id, function(i) read.csv(paste0(i, ".csv"))
}

Or even (no function option) this should work:

lapply(id, function(i) read.csv(paste0(i, ".csv"))

Upvotes: 0

Related Questions