简体   繁体   中英

R: cannot open file 'specdata/001.csv': No such file or directory

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM