0

I'm pretty new to R, and after researching this error extensively, I'm still not able to find a solution. The function i created in R is to determine complete cases in a directory with 332 .csv files.

complete <- function(directory, id = 1:332) {
  s <- vector()
  for (i in 1:length(id)) {
    path <- c(paste(directory, "/",formatC(id[i], width=3, flag=0),".csv",sep=""))   
    data <- c(read.csv(path)) 
    s[i] <- sum(complete.cases(data))
  } 
  dat <- data.frame(cbind(id,nobs=s))   
  return(dat)
}

When i want to test the function, by giving the following command (specdata is the directory where the .csv files are stored)

complete("specdata", 1)

I keep getting the following error:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'specdata/001.csv': No such file or directory
  • I already checked my working directory
  • I checked the files within the directory But i cannot detect any problems there.
  • `path <- c(paste("./",directory, "/",formatC(id[i], width=3, flag=0),".csv",sep=""))` if your directory is a subdirectory of the currently active directory. you can get the currently active directory with getwd() and set it with setwd("/my/folder/path") – Serban Tanasa Jul 14 '15 at 15:44
  • Are you able to open it if you just do `df <- read.csv("specdata/001.csv")`? – maccruiskeen Jul 14 '15 at 15:45
  • > getwd() [1] "/Users/wolterdirkvandam/ Rprogramming/specdata" > df <- read.csv("specdata/001.csv") Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file 'specdata/001.csv': No such file or directory.... so no it doesn't work – Wolter Van Dam Jul 15 '15 at 20:20
  • solved!!! thanks @Serban Tanasa and choff – Wolter Van Dam Jul 15 '15 at 21:22

1 Answers1

0

This is happening because your working directory is not set to the location containing the files. It happened to me as well. I figured it out by hard-coding the location of the directory in my function.

complete<-function(directory,id=1:332)
{
  directory=file.path(getwd())
  observations=0
  counts = c()
  for(i in id)
  {
    name=sprintf("%03d.csv", i)
    data<-read.csv(name, sep="",header= T,na.strings=c("NA","NAN",""))
    data=na.omit(data)
    counts=append(counts, nrow(data))
  }


  df <- data.frame(id=id, nobs=counts)
  df
}
Leigh
  • 28,765
  • 10
  • 55
  • 103