Reputation: 1829
I am trying to read csv files with their names as dates into a for loop and then print out a few columns of data from that file when it is actually there. I need to skip over the dates that I don't have any data for and the dates that don't actually exist. When I put in my code there is no output, it is just blank. Why doesn't my code work?
options(width=10000)
options(warn=2)
for(a in 3:5){
for(b in 0:1){
for(c in 0:9){
for(d in 0:3){
for(e in 0:9){
mydata=try(read.csv(paste("201",a,b,c,d,e,".csv",sep="")), silent=TRUE)
if(class(mydata)=="try-error"){next}
else{
mydata$Data <- do.call(paste, c(mydata[c("LAST_UPDATE_DT","px_last")], sep=""))
print(t(mydata[,c('X','Data')]))
}
}}}}}
Upvotes: 0
Views: 149
Reputation: 57686
That's a really terrible way to read in all your files. Try this:
f <- list.files(pattern="*.csv")
mydata <- sapply(f, read.csv, simplify=FALSE)
This will return a list mydata
of data frames, each of which is the contents of the corresponding file.
Or, if there are other csv files that you don't want to read in, you can restrict the specification:
f <- list.files(pattern="201\\d{5}\\.csv")
And to combine everything into one big data frame:
do.call(rbind, mydata)
Upvotes: 1