0

I have a number of files progressively named from 1 to 22, i.e. "chr1.csv", "chr2.csv" ... "chr22.csv". Each file contains a database with the same variables as columns. I would like to create a loop so as to read these files and save them as elements of a list.

I have tried this snippet of code but it is not working.

file <- vector("character", 22)

data<-vector("list", length = 22)

for (i in 1:22) {
str <- gsub("number", i, "chrnumber.csv")
file[i] <- str
}

for (i in file) {
data <- read.csv(i, sep="")
}
FcmC
  • 143
  • 9
  • 5
    try `files <- list.files(pattern = "^chr\\d+\\.csv", full.names = TRUE);lapply(files, read.csv)` – akrun Jan 14 '19 at 18:18
  • How is it not working? Are you sure your working directory is set to the right folder (with `setwd`)? You might also want to look at `list.files` to get the actual filenames – divibisan Jan 14 '19 at 18:19
  • There's a new package called `tor` available which has a `list_csv` function that will read all `.csv` files from a directory into a list. https://cran.r-project.org/web/packages/tor/tor.pdf – NColl Jan 14 '19 at 19:12

1 Answers1

2

Easier way to create your files vector:

file <- paste0("chr", 1:22, ".csv")

And you have to subset your output list to save the results

data<-vector("list", length = 22) 
names(data)<-file

for (i in file) {
data[[i]] <- read.csv(i, sep="")
}
bbecker
  • 136
  • 3