Why I get this error writing data to a file - r

I have this code
myvector <- c(3.45235, 1.32525, ... , 2.41351) # some numbers
write(myvector, "C:/mypath/myfile.txt") # I use "/" instead of "\"
and I get the following error:
Error in file(file, ifelse(append, "a", "w")) : cannot open the
connection In addition: warning message: In file(file, ifelse(append,
"a", "w")) : cannot open file 'C:/mypath/myfile.txt' : No such file
or directory
I read this tutorial, but I can't understant what's wrong with my code. Any idea?
edit:
As #dickoa pointed out, I need an existing path to write a file, so I tried to simplify in the following way:
file.exists("C:/")
write(myvector, "C:/myfile.txt")
Surprisingly :P the path "C:/" exists (the result is TRUE) but I get a similar error:
Error in file(file, ifelse(append, "a", "w")) : cannot open the
connection
In addition: warning message: In file(file, ifelse(append,
"a", "w")) : cannot open file 'C:/mypath/myfile.txt' : Permission denied

I know #dickoa answered the question in the comments, but in order to provide at least one answer here, I wanted to go through a few simple gotchas with R on Windows.
When you are using Windows, you still have to use forward slashes for paths. In R, backslashes are reserved for escaping values. So a path in R looks like:
C:/path/to/my/directory
In newer variants of Windows, the C:\ is protected from writes by user accounts. If you want to write to the C:\, you must be an administrator. You can accomplish this by right-clicking on the R icon in Windows and choosing "Run as an administrator." This should also be done when you're installing packages. You may not have rights to install packages on certain Windows versions if you don't run it as an administrator.
If you don't want to run R as an administrator, and you want to write to files, you will by default have rights to the C:/Users/username/ directory.
All credit to #dickoa again for his answer in first.
Best of luck!

just adding to answers here.
The reason I was facing this error was, the path I was trying to save in exceded 256 characters, and hence the error.
Problem was sorted once I reduced the path size.

I just shared this answer with a bit of a better explanation here, but the gist of it is:
Try opening the file in Excel to see if it's locked by another user. I was receiving the same error messages and was able to figure out that a colleague had the file open on their computer which had locked me out of the ability to edit it.

Sometimes the problem is in the naming of the file. For example,I have encountered this issue when in the name of the file there was as "\", as there was a dynamic list with names. You can pass by such thing by using something like: sometext = gsub("/"," ", sometext).

It happens when you open the myfile.txt and run the code. Try to close the myfile.txt in your machine and run the command. It solves your problem.

Just another possibility. I have encountered this problem when running the following code. Because I have successfully run this code before this starting RStudio, I run successfully after restarting RStudio this time. So, sometimes, restarting will solve the problem, although I haven't figured out what happened behind.
DT::datatable(
dt.cmbn,
extensions = c('ColReorder','FixedColumns'), rownames = FALSE,
options = list(
colReorder = TRUE,
#dom = 'Bfrtip',
#buttons = I('colvis'),
scrollX = TRUE,
fixedColumns = TRUE
)
)

Related

R unable to write CSVs post update [duplicate]

I am trying to export data in R to a csv file, and as much simple as I try to do it, I always get the same error message. Example:
I create a simple data vector to export
x <- c(1,3,4,3,5,7,5,8,2,5,7)
I try to export with:
write.csv(x,file='whatever.csv')
And I get an error:
error in file(file ifelse (append a w )) cannot open the connection
In addition: Warning message: In file(file, ifelse(append, "a", "w")) :
cannot open file 'whatever.csv': Permission denied
How can I solve this?
First part is to check the working directory and ensure that you have write access to that directory. You can check this with getwd(). I can reproduce your error by trying to write to a directory which is read only.
To set the working directory to something else with read access you can type setwd("H:/foo").
Once you have write access the write.csv(x,file='whatever.csv') should work.
I got the same issue today and I know I have full permission to the folder. What worked for me is giving it the absolute path.
write.csv(data, file="C:/project/file.csv")
If you don't specify a filename (i.e. C:/temp.csv) and just provide a file path, this same error pops up with both write.csv and write_csv.
I got this error today and fixed it by granting everyone write permission to the folder.
Steps: locate the folder on your PC, right-click and select properties, look for the "Security" tab and edit the permission for all to include "Write"
I got this error today because the file I try to rewrite on was open in another program. After I closed it, the problem solved.
Related: I was trying to save a csv to a relative path, that I built incrementally in Windows, but in my case the problem wasn't an error really, but a misunderstanding on my part - in the following code:
library(dplyr)
library(hflights)
path_to_hflights_as_csv <-
file.path(path.expand("~/MyHomeSubDir"),
"hflights.csv")
write.csv(hflights, path_to_hflights_as_csv)
path.expand("~/MyHomeSubDir") is mapped to "C:/Users/my.username/Documents/MyHomeSubDir" instead of "C:/Users/my.username/MyHomeSubDir".
Searching if it was some faulty config while installing R, I found that "home dir" in various Windows versions is indeed "C:/Users/my.username/Documents/" (and not "C:/Users/my.username"):
https://en.wikipedia.org/wiki/Home_directory
https://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f
And when you pass a path including a sub directory that doesn't exist to utils::csv.write the error is similar (only the reason to not opening file is different - cannot open file 'C:/Users/my.username/MyHomeSubDir/hflights.csv': No such file or directory).
I just stumbled across this question in trying to figure it out myself. I had the exact same error message pop up a few times:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
After searching around and finding nothing that worked for me I restarted R and received the same message, but also a new error:
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file 'censoredpath.file.csv': Permission denied
I went to my file explorer and attempted to open the .csv in Excel and it notified me that it was locked by another user (someone else had the file open on their computer). So if it's not a problem with having access to the directory like what's already been suggested, try opening it in Excel to see if that might be the problem.
In case you tried everything and did not work, check your antivirus. In my case AVAST was causing this issue for some reason.

How to Load R Work Space with Unknown File Type

I saved my R Work Space yesterday but it is showing as an unknown file type in my folder (literally under "Type" it just says "File"). I would now like to reload the Work Space but got the following error message.
Any suggestions on how to reload the Work Space would be greatly appreciated!
I tried to open the Work Space by right clicking to go to "Open With" but R doesn't show up as one of the programs that I could use to open the file.
load("Segmentation.RData")
Error in readChar(con, 5L, useBytes = TRUE) : cannot open the
connection In addition: Warning message: In readChar(con, 5L, useBytes
= TRUE) : cannot open compressed file 'Segmentation.RData', probable reason 'No such file or directory'
As the error message suggests, the file might simply not be found. But the trick here is, that the file cannot be found where R thinks it is.
When you start R anew, check that it is running in the correct directory with
getwd()
Is it running where you think it was? If not, change it! Depending on the interface (console, RGui or RStudio) there are some different dialogs for this, but you can always trust good ol' setwd. But mind you if you are using Windows, then you should replace the backslashes (\) with forward slashes (/)!
Once satisfied that R is running in the correct directory, try list.files() and see if the file is found. It might not be called what you were believing it should have been. You can also try file.exists("Segmentation.RData").
If R is running in the correct directory and R can find the file, and R still does not want to load the .RData file, it might simply be corrupt - or something else entirely.

when downloading or saving a file in r I can't make R create a directory

Whenever I want to download something to a folder, I have to create the folder manually first.
for instance:
download.file("https://ndownloader.figshare.com/files/2292169",
"data2/portal_data_joined.csv")
Will give me an error
cannot open destfile 'data2/portal_data_joined.csv', reason 'No such file or directory'
My solution is to manually create a folder data2 and then it works.
My question is: Why doesn't R have the right to create a folder?
R has the right, but it chooses not to. It would seem to be fairly common practice to not create folders when R makes a file:
> write.table(x,file="./foo/bar/baz.csv")
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file './foo/bar/baz.csv': No such file or directory
A neat solution is to create a function, here called makepath, that creates the folder at any depth and returns the path back:
> makepath = function(path){dir.create(dirname(path),recursive=TRUE);path}
Then you can do:
> write.table(x,file=makepath("./foo/bar/baz.csv"))
> write.table(x,file=makepath("./foo/bar/qux/moo/baz.csv"))
And similarly for download.file in your case.
Use dir.create to create the dir first :)
as Rich Scriven said:
download.file does not create destfile for you. You have to create it first, before you can download to it. Some other functions create files, but not download.file
and Felipe Gerard said:
To create the directory from R use dir.create("folder")

Cannot export data to a file in R (write.csv)

I am trying to export data in R to a csv file, and as much simple as I try to do it, I always get the same error message. Example:
I create a simple data vector to export
x <- c(1,3,4,3,5,7,5,8,2,5,7)
I try to export with:
write.csv(x,file='whatever.csv')
And I get an error:
error in file(file ifelse (append a w )) cannot open the connection
In addition: Warning message: In file(file, ifelse(append, "a", "w")) :
cannot open file 'whatever.csv': Permission denied
How can I solve this?
First part is to check the working directory and ensure that you have write access to that directory. You can check this with getwd(). I can reproduce your error by trying to write to a directory which is read only.
To set the working directory to something else with read access you can type setwd("H:/foo").
Once you have write access the write.csv(x,file='whatever.csv') should work.
I got the same issue today and I know I have full permission to the folder. What worked for me is giving it the absolute path.
write.csv(data, file="C:/project/file.csv")
If you don't specify a filename (i.e. C:/temp.csv) and just provide a file path, this same error pops up with both write.csv and write_csv.
I got this error today and fixed it by granting everyone write permission to the folder.
Steps: locate the folder on your PC, right-click and select properties, look for the "Security" tab and edit the permission for all to include "Write"
I got this error today because the file I try to rewrite on was open in another program. After I closed it, the problem solved.
Related: I was trying to save a csv to a relative path, that I built incrementally in Windows, but in my case the problem wasn't an error really, but a misunderstanding on my part - in the following code:
library(dplyr)
library(hflights)
path_to_hflights_as_csv <-
file.path(path.expand("~/MyHomeSubDir"),
"hflights.csv")
write.csv(hflights, path_to_hflights_as_csv)
path.expand("~/MyHomeSubDir") is mapped to "C:/Users/my.username/Documents/MyHomeSubDir" instead of "C:/Users/my.username/MyHomeSubDir".
Searching if it was some faulty config while installing R, I found that "home dir" in various Windows versions is indeed "C:/Users/my.username/Documents/" (and not "C:/Users/my.username"):
https://en.wikipedia.org/wiki/Home_directory
https://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f
And when you pass a path including a sub directory that doesn't exist to utils::csv.write the error is similar (only the reason to not opening file is different - cannot open file 'C:/Users/my.username/MyHomeSubDir/hflights.csv': No such file or directory).
I just stumbled across this question in trying to figure it out myself. I had the exact same error message pop up a few times:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
After searching around and finding nothing that worked for me I restarted R and received the same message, but also a new error:
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file 'censoredpath.file.csv': Permission denied
I went to my file explorer and attempted to open the .csv in Excel and it notified me that it was locked by another user (someone else had the file open on their computer). So if it's not a problem with having access to the directory like what's already been suggested, try opening it in Excel to see if that might be the problem.
In case you tried everything and did not work, check your antivirus. In my case AVAST was causing this issue for some reason.

How to import files into R?

I'm a new user to R, sorry if my question is too basic.
I've installed the newest version of R on windows 7 and as a practice, i tried to open a .txt file using
students<-read.table("students.txt",header=T,sep="\t")
but there's always an error message as follows:
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'students.txt': No such file or directory
I've already changed the directory to where the students.txt resides; but it just doesn't work. Please help!
Thank you very much in advance if anyone can help me solve the problem.
There is an entire R manual devoted to data import / export questions.
Now, if you fail to specify file name and path correctly, use the file.choose() function instead which allows you to point, click and shoot:
students<-read.table(file.choose(),header=T,sep="\t")
The error message is saying that it cannot find the students.txt file. You should try two things:
Call getwd() and confirm that the file is in the directory that is returned.
Try specifying the full path to the file in your read.table() call.
Look at help("read.table") for more detail on the function. You may, for instance, want to change the default to stringsAsFactors=FALSE, depending on your application.
If you use RStudio, which I thoroughly recommend, then you can create a Project with it's own directory. read.csv and friends will then read from that directory by default, which makes it all nice and easy.
This works with R:
first copy the table; then open up R and type:
c <- read.table("clipboard")
then press Enter.

Resources