Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

  1. 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
  2. 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.
  3. 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...