66

I'm new to R, and after researching this error extensively, I'm still not able to find a solution for it. Here's the code. I've checked my working directory, and made sure the files are in the right directory. Appreciate it. Thanks

pollutantmean <- function(directory, pollutant = "nitrate", id= 1:332)            
{                 if(grep("specdata",directory) ==1) 
            {
                    directory <- ("./specdata")
            }
            mean_polldata <- c()
            specdatafiles <- as.character(list.files(directory))
            specdatapaths <- paste(directory, specdatafiles, sep="")
                            for(i in id) 
                    {
                    curr_file <- read.csv(specdatapaths[i], header=T, sep=",")
                    head(curr_file)
                    pollutant
                    remove_na <- curr_file[!is.na(curr_file[, pollutant]), pollutant]
                    mean_polldata <- c(mean_polldata, remove_na)
                    }
            {
                    mean_results <- mean(mean_polldata)
                    return(round(mean_results, 3))
            }
} 

The error I'm getting is below:

Error in file(file, "rt") : cannot open the connection

file(file, "rt")

read.table(file = file, header = header, sep = sep, quote = quote, 
    dec = dec, fill = fill, comment.char = comment.char, ...)

read.csv(specdatapaths[i], header = T, sep = ",")

pollutantmean3("specdata", "sulfate", 1:10)

In addition: Warning message:
In file(file, "rt") :
  cannot open file './specdata001.csv': No such file or directory
Houmles
  • 197
  • 11
ldeassis
  • 785
  • 1
  • 5
  • 7
  • 4
    It looks like you have (??) a directory `specdata` with files `001.csv`, etc. Then the proper path is `./specdata/001.csv`, *not* `./specdata001.csv`. Try changing `sep=""` to `sep="/"` in the `specdatapaths` line. – jlhoward Dec 14 '14 at 04:36
  • 2
    Or try Degugging 101 tactics like printing the values that are being givne to the function throwing the error. – IRTFM Dec 14 '14 at 05:42
  • Thank you both for your replies. I was able to fix the open connection error, but now I'm getting a "unidentified columns selected" error. Any suggestions? Thanks pollutantmean("specdata", "sulfate", 1:10) Error in `[.data.frame`(curr_file, , pollutant) : undefined columns selected 6 stop("undefined columns selected") 5 `[.data.frame`(curr_file, , pollutant) 4 curr_file[, pollutant] 3 `[.data.frame`(curr_file, !is.na(curr_file[, pollutant]), pollutant) 2 curr_file[!is.na(curr_file[, pollutant]), pollutant] 1 pollutantmean("specdata", "sulfate", 1:10) – ldeassis Dec 14 '14 at 21:00
  • 3
    You should ask that as a separate question. Multiline code is pretty much unreadable in comments. – Stewart Macdonald Jul 26 '15 at 05:49
  • 3
    Hail to the question, for aiding all future r users who may face this. – bonCodigo Apr 09 '17 at 06:02
  • Looks under *nix (and Mac), you would need set full path either using assigning `directory` or calling `setwd` function... – lkahtz Jan 21 '19 at 08:43

17 Answers17

39

You need to change directory <- ("./specdata") to directory <- ("./specdata/")

Relative to your current working directory, you are looking for the file 001.csv, which is in your specdata directory.

This question is nearly impossible to answer without any context, since you have not provided us with the structure of your working directory here. Fortunately for you, I have already taken R Programming on Coursera, so I already did this homework question.

capt-calculator
  • 722
  • 5
  • 12
  • The general solution would be to add setwd("/absolute/path/of/directory/with/required/files/") at the beginning. – kvaibhav Jan 13 '17 at 10:52
  • 1
    I kept changing the working directory and my working files' folder was inside this dir. Still Rstudio failed to go into files' folder. So yeah, had to type in the whole lot after user/home folder. (This is in Mac though). – bonCodigo Apr 09 '17 at 06:02
27

The reason why you see this error I guess is because RStudio lost the path of your working directory.

(1) Go to session...

(2) Set working directory...

(3) Choose directory...

--> Then you can see a window pops up.

--> Choose the folder where you store your data.

This is the way without any code that you change your working directory. Hope this can help you.

enter image description here

BetterTeng
  • 419
  • 5
  • 7
14

Set your working directory one level/folder higher. For example, if it is already set as:

setwd("C:/Users/Z/Desktop/Files/RStudio/Coursera/specdata")

go up one level back and set it as:

setwd("C:/Users/Z/Desktop/Files/RStudio/Coursera")

In other words, do not make "specdata" folder as your working directory.

WEFX
  • 8,298
  • 8
  • 66
  • 102
Abi
  • 149
  • 1
  • 2
11

I just spent a lot of time trying to understand what was wrong on my code too...

And it seems to be simple if you are using windows.

When you name your file "blabla.txt" then windows name it "blabla.txt.txt"... That's the same with .CSV files so windows create a file named "001.csv.csv" if you called it "001.csv"

So, when you create your .csv file, just rename it "001" and open it in R using read.table("/absolute/path/of/directory/with/required/001.csv")

It works for me.

IceCriime
  • 111
  • 1
  • 2
3

close your R studio and run it again as an administrator. That did the magic for me. Hope it works for you and anyone going through this too.

Joshua Jumbo
  • 69
  • 1
  • 10
2

If running on Windows try running R or R Studio as administrator to avoid Windows OS file system constraints.

2

One better check that can be done if you get such error while accessing a file is to use the file.exists("file_path/file_name") function. This function will return TRUE if the file is existing and accessible, else False.

akzhere
  • 323
  • 4
  • 11
2

Got this error and found that RStudio on my Windows machine try to use \ as escape symbol, so had to replace it with \\ to deal with it.

Try file.exists function with your path, e.g.:

file.exists("D:\\R\\path_to_file.csv")
Mikhail Tumashenko
  • 1,683
  • 2
  • 21
  • 28
1

Use setwd() to change to appropriate directory. Use only filename to access any file in the working directory. Navigate a folder above by using "../<filename>".

Rishiraj Surti
  • 117
  • 1
  • 6
1

Error in file(file, "rt") :

I just faced the same error and resolved by removing spacing in address using paste0 instead of paste

filepath=paste0(directory,"/",filename[1],sep="")
mabdullahse
  • 3,474
  • 25
  • 23
0

I got this same error message and fixed it in the easiest way I could. I put my .csv file into a file folder on my desktop, opened desktop in the window next to console on RStudio, and then opened my file there, and checked the box next to my .csv file, then I used the "more" pull down menu at the top of this window to set this as my working directory...probably the easiest thing for SUPER beginners like me :)

0

This error also occurs when you try to use the result of getwd() directly in the path. The problem is the missingness of the "/" at the end. Try the following code:

projectFolder <- paste(getwd(), "/", sep = '')

The paste() is to concatenate the forward slash at the end.

Guannan Shen
  • 649
  • 8
  • 12
0

I got my R code file from a friend and was not able to run read.csv command but If I copy the same command(read.csv ) to a new R script file, it ran fine.

Below command was not running in R code file shared by my friend, working directory,file name etc were all correct because If I created a new R script file and ran below command ,it worked.

           df <- read.csv("file.csv",header=TRUE,stringsAsFactors = FALSE,strip.white = 
           TRUE,sep = ',')

issue/resolution: I right clicked the R code file and unblocked the file and click save button and issue got resolved. I your R code file is in Downloads folder in windows , then move to some other folder.

enter image description here

Tokci
  • 1,220
  • 1
  • 23
  • 31
0

I had a same issue .I removed the extension from the file name.Example my file name was saved as xyz. csv. i saved it as xyz.

ns28
  • 51
  • 1
  • 10
0

Error in file(file, "rt")

Created a .r file and saved it in Desktop together with a sample_10000.csv file.

Once trying to read it

heisenberg <- read.csv(file="sample_100000.csv")

was getting the same error as you

heisenberg <- read.csv(file="sample_10000") Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file 'sample_10000': No such file or directory


I knew at least two ways to fix this, one using the absolute path and the other changing the working directory.

Absolute path

I fixed it adding the absolute path to the file, more precisely

heisenberg <- read.csv(file="C:/Users/tiago/Desktop/sample_100000.csv")

Working directory

This error shows up because RStudio has a specific working directory defined which isn't necessarily the place the .r file is at.

So, to fix using this approach I've gone to Session > Set Working Directory > Chose Directory (CTRL + Shift + H) and selected Desktop, where the .csv file was at. That way running the following command also worked

heisenberg <- read.csv(file="sample_100000.csv")
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
0

I was getting the same error when trying to import 10,000 files. I tried opening a single file with Excel and Excel gave me an error message: "the file path is too long".

The file was buried in 6 nested folders, which is a problem of itself. Moving all the files to a desktop folder solved the issue without having to change any code.

Madisonel
  • 105
  • 9
0

I came across a solution based on a few answers popped in the thread. (windows 10)

setwd("D:/path to folder where the files are")
directory <- getwd()
myfile<- "a_file_in_the_folder.txt"
filepath=paste0(directory,"/",myfile[1],sep="")
table <- read.table(table, sep = "\t", header=T, row.names = 1, dec=",")
Leonardo
  • 85
  • 7