-3

In R, I am making a function that requires reading in 1:n csv files, how to I name each file in a "for" loop and save. I have tried test[i] <- read.csv(paste0("0", "0", i, sep="") and I get a "closure" error. I have searched through Stack Overflow and found similar questions but nothing like I am looking for. I am using also 1 "if" statement and two "else if" statements in the "for" loop. There are 3 different paste0 functions, paste0("0", "0", i, ".csv", sep = ""), paste0("0", i, ".csv" sep = ""), and paste0(i, ".csv", sep "")

I just signed up to Stack Overflow today and I am new to R. I am sorry if I overlooked the question and it has been answered.

What I am looking for is something like name_test[1] <- 001.csv and so on.

figurine
  • 746
  • 9
  • 22
  • 2
    See my answer here: http://stackoverflow.com/a/24376207/903061 – Gregor Thomas Apr 24 '15 at 17:17
  • Lots on this problem already on SO - try Googling for "stackoverflow getmonitor". Instead of using `paste0` and a loop to read the files, consider `list.files()` with argument `full.names = TRUE` to get the list of files in a directory - then you can use `lapply` with `read.csv` to process, as described elsewhere on StackOverflow. Such an approach would be useful even if they weren't all named `001.csv`, `002.csv`, etc. – Sam Firke Apr 24 '15 at 18:27

2 Answers2

0

Perhaps something like this will work (not tested):

test <- lapply(1:n, function(i) read.csv(paste(sprintf("%03d", i), "csv", sep=".")))
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
0

If you want to import all the data into a list, you can try this

# Get the list of files in the folder
db.name.list<-list.files(path="path", pattern="*.csv")
# Read in all the data into a list of dataframe
db.name.path<-paste("path",db.name.list, sep="/")
db<-lapply(db.name.path, read.csv, header=T)
names(db)<-db.name.list
Hao
  • 7,476
  • 1
  • 38
  • 59