Michael Kozak
Michael Kozak

Reputation: 99

Using variable in read csv command in r

I have a folder with many csv files and I want to make a function that will receive as an argument a numeric range by which the function will pick the selected files (named 1.csv, 2.csv, etc.) and insert them into one data frame. I tried:

fun <- function(range){
  for( i in range){
    dat <- read.csv("K:/R program/",i,".csv")
  }
  dat
}

I have a few problems. First, I'm probably running over the data each iteration. Second, the read function is not working and making error.

Upvotes: 0

Views: 1913

Answers (2)

Daniel
Daniel

Reputation: 7832

sprintf should work, like eg

for (i in 1:length(urls)) {
  download.file(urls[i], sprintf("~/Desktop/rstats/temp%i.csv.gz", i))
}

And to avoid overwriting your data, init the data frame and bind rows in each for-step.

df <- data.frame()
library(dplyr)

for (i in 1:length(urls)) {
  df.csv <- read.csv(sprintf("~/Desktop/rstats/temp%i.csv", i))
  dummy.df <- df.csv %>% dplyr::select(date, package, version, country)
  df <- dplyr::bind_rows(df, dummy.df)
}

Upvotes: 0

Gavin Simpson
Gavin Simpson

Reputation: 174948

There are two problems:

  1. You are overwriting dat at each iteration, and
  2. You are passing arguments to read.csv(), not pasting parts of the filename into a single string.

The file.path() function is usually useful here, but it is more convenient to use paste0() here as you have part of the file name in a variable and the extension needs to be added. I might try (making some assumptions about your data)

fun <- function(range, ...){
  dat <- vector(mode = "list", length = length(range))
  for (i in seq_along(range)){
    path <- paste0("K:/R program", range[i], ".csv")
    dat[[i]] <- read.csv(file = path, ...)
  }
  dat
}

Some explanation, line by line:

  1. Create a list object to hold the data
  2. Setup loop, but make i be an integer index i = {1, 2, ..., n}
  3. Build up the path using paste0()
  4. Read the data file and assign it to the ith element of dat
  5. Return dat

Upvotes: 1

Related Questions