R: setwd delay when using file.choose - r

So what im doing is making my browse button so that when i click on them bring the user straight to the directory that i want them to save their file in or look for their file.
For example
setwd("C:\\Users\\Eric\\Desktop\\Program\\graphs") #set directory
file.choose()
However in the earlier script i have already set my work directory at
setwd("C:\\Users\\Eric\\Desktop\\Proram") #set directory
so when i ran the first example it brought me to directory Program instead of graphs .
but when i ran file.choose() on the second time, it then brought me to the graphs directory
why is this happening? any idea how to fix this ?

Here's a quick and dirty solution to your problem:
dirPath <- "C:\\Users\\Eric\\Desktop\\Program\\graphs"
setwd(dirPath)
# Tell R to sleep until the current directory matches the expected directory
while(getwd() != normalizePath(dirPath)) {
Sys.sleep(0.02)
}
file.choose()

Related

No such file or directory in R studio [duplicate]

I have an excel file that I want to open in R. I tried both of these commands after saving the excel file as a csv file or a text file.
read.table() or read.csv()
I think part of the problem is where the file is located. I have it saved on the desk top. What am I missing here?
Here is the R output
In file(file, "rt") :
cannot open file 'Rtrial.csv': No such file or directory
> help.search("read.csv")
> read.csv("Rtrial.csv")
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'Rtrial.csv': No such file or directory
> read.table("tab")
To throw out another option, why not set the working directory (preferably via a script) to the desktop using setwd('C:\John\Desktop') and then read the files just using file names
Try
f <- file.choose()
to choose the file interactively and save the name in f.
Then run read.csv on the saved filename
d <- read.csv(f)
Sound like you just have an issue with the path. Include the full path, if you use backslashes they need to be escaped: "C:\\folder\\folder\\Desktop\\file.csv" or "C:/folder/folder/Desktop/file.csv".
myfile = read.csv("C:/folder/folder/Desktop/file.csv") # or read.table()
It may also be wise to avoid spaces and symbols in your file names, though I'm fairly certain spaces are OK.
I had to combine Maiasaura and Svun answers to get it to work: using setwd and escaping all the slashes and spaces.
setwd('C:\\Users\\firstname\ lastname\\Desktop\\folder1\\folder2\\folder3')
data = read.csv("file.csv")
data
This solved the issue for me.
Here is one way to do it. It uses the ability of R to construct file paths based on the platform and hence will work on both Mac OS and Windows. Moreover, you don't need to convert your xls file to csv, as there are many R packages that will help you read xls directly (e.g. gdata package).
# get user's home directory
home = setwd(Sys.getenv("HOME"));
# construct path to file
fpath = file.path(home, "Desktop", "RTrial.xls");
# load gdata library to read xls files
library(gdata);
# read xls file
Rtrial = read.xls(fpath);
Let me know if this works.
Save as in excel will keep the file open and lock it so you can't open it. Close the excel file or you won't be able to use it in R.
Give the full path and escape backslashes read.csv("c:\\users\\JoeUser\\Desktop\\JoesData.csv")
I have experienced that this error occurs when you either move the excel file to the destination other than where your r file is located or when you move your r file to the destination other than where your excel file is located.
Good Practice:
Keep your .r and .csv files in the same directory.
open your .r file from getting into its directory instead of opening the r file from rstuio's open file option.
You also have import Dataset option at Environment Block, just click there and get your required packages installed & from next time use this option to read datasets. You will not get this error again.
I also appreciate the above provided answers.
Another way of reading Excel including the new format xlsx could be the package speedR (https://r-forge.r-project.org/projects/speedr/). It is an interactive and visual data importer. Besides importing you can filter(subset) the existing objects from the R workspace.
My issue was very simple, the working directory was not the "Source" directory that was printed when the file ran. To fix this, you can use getwd() and setwd() to get your relative links working, or just use a full path when opening the csv.
print(getwd()) # Where does the code think it is?
setwd("~/Documents") # Where do I want my code to be?
dat = read.csv("~/Documents/Data Visualization/expDataAnalysis/one/ac1_survey.csv") #just make it work!
MAC OS It happened to me as well. I simply chose from the R toolbar MISC and then chose Change Working Directory. I was able to choose the directory that the .csv file was saved in. When I went back to the command line and typed getwd() the full directory was updated and correct and the read.csv function finally worked.
I had the same problem and when I checked the properties of the file on file explorer, it shows me the next message:
"Security: This file came from another computer and might be blocked to help protect this computer"
You click on the "Unblock" button and... you can access to the file from R without any problem, just using read.csv() function and from the directory specified as your working directory, even if is not the same as the file’s directory you are accessing to.
I just had this problem and I first switched to another directory and then switched back and the problem was fixed.
this work for me, accesing data from root. use double slash to access address.
dataset = read.csv('C:\\Users\\Desktop\\Machine Learning\\Data.csv')
Kindly check whether the file name has an extension for example:
abc.csv
if so remove the .csv extension.
set wd to the folder containing the file (~)
data<-read.csv("abc.csv")
Your data has been read the data object
In my case this very problem was raised by wrong spelling, lower case 'c:' instead of upper case 'C:' in the path. I corrected spelling and problem vanished.
You can add absolute path to the file
heisenberg <- read.csv(file="C:/Users/tiago/Desktop/sample_100000.csv")
If really want to run something like
heisenberg <- read.csv(file="sample_100000.csv")
then you'll have to change the working directory to match the place the .CSV file is at. More about it here.

setwd() works weird inside a function?

I have a function for choosing files using file.choose(). When I call it inside a script I want it open certain directory where I wish to choose files. There is a cycle inside the function as I need to choose a bunch of files. First time it opens in the working directory, which is predictable. I put setwd() inside to make the needed directory as working directory so I can choose files there. But when dialog box opens next time it is again the old working directory. But next time it is the directory I need. If I choose different folders it works the same - next time the old directory but after that the new one. I wrote a short function that reproduces behavior:
foo <- function() {
files <- NULL
for (i in c(1,2,3,4,5)) {
x <- file.choose()
y <- dirname(x)
setwd(y)
print(y)
print(getwd())
}
}
Just call this function and try to choose files in different or same directories. You can see that directory name is new and getwd() says that new working directory is set but next file choice dialog opens in previous directory.
Please keep in mind that I need to use file.choose() function as it works on a headless OS, both Windows and Unix-like.
When I don't use setwd() it is always the old working directory.

Why doesn't choose.files() open in the current working directory?

When I change the working directory (e.g., from dir1 to dir2) then try to use choose.files(), the first time choose.files() runs it goes to dir1. If I cancel and run choose.files() a second time, then it opens in dir2. How can I get choose.files() to open in the most current working directory?
I was encountering a different issue with file.choose() so I'm not
able to use that function as a replacement
Here's an example:
getwd() # say this is dir1
setwd(choose.dir()) # here I change the wd to dir2
getwd() # currently set to dir2
choose.files() # this opens in dir1
choose.files() # this time it opens in dir2
I'd like to be able to use this progression to select a file from the current working directory. Appreciate any ideas. Thanks!
Try adding this mask to the default argument:
choose.files(default=paste0(getwd(), "/*.*"))
From the help for ?choose.files:
If you would like to display files in a particular directory, give a
fully qualified file mask (e.g., "c:\*.*") in the default argument.

Calling Skim from inside R

I'm making a simple line in r to automatically open my generated plots.
I output the plots to a file called "plots.pdf" in the same directory as my r file, and at the end i use this two lines to try to open it:
dir <- paste("/Applications/Skim.app/Contents/MacOS/Skim ",getwd(),"/plots.pdf",sep="")
system(dir)
Basically, dir concatenates the full path of the skim app and the full path of the generated plot.
If i run the string stored at dir in a shell it works perfect, it opens the pdf file in Skim, but when i run it with system() from inside R it doesn't work (Skim says 'The document “plots.pdf” could not be opened.').
I believe this is a very little mistake somewhere in the syntax regarding the absolute/relative paths, but haven't managed to find it... Any advice is welcome! (Or a better way to achieve the same)
I found a way to bypass that problem, i just changed the path to Skim for the 'open' command and i let the system to assign the default app for pdf viewing. So:
dir <- paste("open ",getwd(),"/plots.pdf",sep="")
And it works.

How do I open a script file in RStudio using an R command?

I have a simple script file called test.R. It's saved in the working directory. When I go to File > Open > test.R, it opens the file in the editor (without executing the code, which is what I want).
How do I do this by typing a command in the console window? To be clear, I just want to open (not execute) the file.
You are looking for file.edit
file.edit('test.R')
should open the file in an editor (if you are in RStudio, this should default to RStudio)
It appears that if you are using RStudio then another option is to use rstudioapi::navigateToFile("test.R")
I had the same issue that utils::file_edit() within my package opens outside R-studio. I changed it to usethis::edit_file(). With this function the file opens inside R-studio.
Another alternative is the shell.exec function.
shell.exec("text.R") # This will open the file or URL using the path associated with it
Also, I think for your use case. This code snippet might be a little bit useful.
file <- "example.csv"
sub_dir <- "subdirectory"
dir.create(sub_dir)
writeLines("myfile",file.path(sub_dir, file))
# Works
shell.exec(file.path(sub_dir, file, fsep = "\\"))
shell.exec(file.path(sub_dir, file))

Resources