When I setwd using Rstudio IDE GUI, then I go to create a new file... the default working directory is not the current working directory. What is a better Workflow? Any .Rprofile commands to always save in the working directory?
pic 1
pic 2
As mentioned in the comments, using a project would certainly help. Projects will always set the working directory to the project root folder on opening. Additionally, previous commands and working environment is saved (if you want it to be), so you can get right back to where you were. This is especially useful if you are working on different assignments.
Additionally, you can use getwd() to get your current working directory. Remember that the RStudio file-browser doesn't update when you set your working directory in R.
Related
Disclaimer: I am very new here.
I am trying to learn R via RStudio through a tutorial and very early have encountered an extremely frustrating issue: when I am trying to use the read.table function, the program consistently reads my files (written as "~/Desktop/R/FILENAME") as going through the path "C:/Users/Chris/Documents/Desktop/R/FILENAME". Note that the program is considering my Desktop folder to be through my documents folder, which is preventing me from reading any files. I have already set and re-set my working directory multiple times and even re-downloaded R and RStudio and I still encounter this error.
When I enter the entire file path instead of using the "~" shortcut, the program is successfully able to access the files, but I don't want to have to type out the full file path every single time I need to access a file.
Does anyone know how to fix this issue? Is there any further internal issue with how my computer is viewing the desktop in relation to my other files?
I've attached a pic.
Best,
Chris L.
The ~ will tell R to look in your default directory, which in Windows is your Documents folder, this is why you are getting this error. You can change the default directory in the RStudio settings or your R profile. It just depends on how you want to set up your project. For example:
Put all the files in the working directory (getwd() will tell you the working directory for the project). Then you can just call the files with the filename, and you will get tab completion (awesome!). You can change the working directory with setwd(), but remember to use the full path not just ~/XX. This might be the easiest for you if you want to minimise typing.
If you use a lot of scripts, or work on multiple computers or cross-platform, the above solution isn't quite as good. In this situation, you can keep all your files in a base directory, and then in your script use the file.path function to construct the paths:
base_dir <- 'C:/Desktop/R/'
read.table(file.path(base_dir, "FILENAME"))
I actually keep the base_dir assignemnt as a code snippet in RStudio, so I can easily insert it into scripts and know explicitly what is going on, as opposed to configuring it in RStudio or R profile. There is a conditional in the code snippet which detects the platform and assigns the directory correctly.
When R reports "cannot open the connection" it means either of two things:
The file does not exist at that location - you can verify whether the file is there by pasting the full path echoed back in the error message into windows file manager. Sometimes the error is as simple as an extra subdirectory. (This seems to be the problem with your current code - Windows Desktop is never nested in Documents).
If the file exists at the location, then R does not have permission to access the folder. This requires changing Windows folder permissions to grant R read and write permission to the folder.
In windows, if you launch RStudio from the folder you consider the "project workspace home", then all path references can use the dot as "relative to workspace home", e.g. "./data/inputfile.csv"
I've been building an R package via an R project file (.Rproj) in R studio with the project file linked to my github. When I was working on it this morning, all was as it should be, but when I returned to it this afternoon, the .Rproj file had mysteriously vanished. All other files and folders associated with the package are where they should be (e.g., the "R" folder with the scripts for the package's functions, the DESCRIPTION file, the man folder, etc.) but the .Rproj file is gone. I have not deleted it and it is not in my trash can, nor does git have any record of it for some reason.
If I do a search for the file name in the windows search bar (I'm suing windows 7, btw) the file shows up and says that it is in the correct location, but if I click on it, I get an error message saying that the file has been moved or deleted. Similarly, if I try to navigate to where the file should be via "open project" in R, there is a greyed out ".Rproj.user" folder that I don't recall having seen before, but no project file.
I'm at my wits end for what is going on. The package on github appears to all still be correct (as do the files on my computer), but without being able to find or access the .Rproj file I can't easily edit the package and push the changes to github.
Does anyone have any idea what is going on or how to retrieve my package file? Since I have all the source files for it, I could always build a new project using the source files, but then I need that to link up to my github which is linked to a now non-existent project file, and everything becomes really messy and tedious quickly.
PS I have restarted both my computer and R. It didn't help.
You can probably just create a "new" project in the existing folder to generate a new .Rproj file.
The .Rproj file doesn't actually do that much. It mostly lets RStudio know that "this folder is the root directory of a project named X". Git keeps its own hidden files in the directory to track things (that RStudio will look for if it's a project).
If you haven't done this, I'd also recommend adding your .Rproj files to your .gitignore file - Rproj files are user-specific so shouldn't be tracked in version control. (If you used RStudio to create the git repo, this will be done automatically.)
I'm using GIT and I note that if I just move the whole folder (or rename it) in windows, that it breaks all the paths. I then end up in an infinite loop of trying to quit Rstudio and Rstudio unable to find the file path to save (or not save).
Is there a way to move the location of the project folder while keeping it still intact?
Sorry, let me make this clearer.
Start Rstudio and create a version-controlled project (I'm using GIT)
Realize that you put the project in the wrong folder of your computer
Move the project to the new folder by (a) moving the Rstudio and GIT files to another location using windows explorer. (breaking all the links) or (b) start a new project in the 'correct' location. (losing the versions of your edits).
With RStudio closed, I moved the project folder (using Windows Explorer) to a new location. My RStudio project opened fine from there. I made an edit and pushed it to Github.
If you use the here package on Cran you won't have to update any links.
If you use GitHub Desktop, it will detect that the project has been moved and allow you to locate (set) it to a different folder.
I use R under Windows on several machines.
I know you can set the working directory from within an R script, like this
setwd("C:/Documents and Settings/username/My Documents/x/y/z")
... but then this breaks the portability of the script. It's also annoying to have to reverse all the slashes (since Windows gives you backslashes)
Is there a way to start R in a particular working directory so that you don't need to do this at the script level?
You should copy shortcut to R (R.lnk file) to desire folder. Then in "Properties" (right mouse button -> last option) delete anything in field "Start in..." in second tab ("Shortcut"?). If you start R with this shortcut working directory will be that one where the shortcut is.
I don't have english version of Windows so I'm not sure about field names, but they should be easy to find.
Similar questions were in R-windows-faq:
2.5 How do I run it?
2.10 How can I keep workspaces for different projects in different directories?
2.14 What are HOME and working directories?
In 2.14 is mentioned that
The working directory is the directory from which Rgui or Rterm was launched, unless a shortcut was used when it is given by the `Start in' field of the shortcut's properties.
You could use an environmental variable. This can work with Sys.getenv() and Sys.setenv(). For instance:
> Sys.setenv(R_TEST="testit")
> Sys.getenv("R_TEST")
R_TEST
"testit"
If you sent the variable in your script, you should be able to access it from within, and then call setwd() on that output.
Save your workspace to the desired directory and thereafter you just open the workspace from Windows explorer.
I put the following line in front of my scripts and it allows me to work across my computers.
setwd(path.expand("~/path/to/working/directory/") )
where ~ is = to your home directory.
Sys.setenv(HOME = "path") or Sys.setenv(R_USER = "path") can both set the home directory.
In my case, I work on several windows boxes, each have fairly different directory structures, but by setting the home directory properly I can sync code between computers and have them run properly on each one since where I run my R projects have similar directory structures.
If you're using Emacs/ESS, this isn't a problem. I navigate to the directory where my R script is located, open it, then start an R ESS process. An R console pops up with the current directory as R's working directory.
If you haven't converted to Emacs/ESS, I recommend it. (Though to prevent a flame war, I also note there are similar options for Vi users.)
Hope that helps.
Just a detail: instead of reversing the slashes as you say, just add another backslash. Two of these \\ works the same way as one of these /. That makes it at least a little easier.
For Ubuntu:
Insert the following command into your .Rprofile file (usually in your home directory):
setwd(Sys.getenv("PWD"))
Now your default working directory will be whatever directory you launched R from. Keep in mind you can also set up default workspaces in different directories by saving your workspace image as .RData wherever you plan to launch R (startup sources .Rprofile before searching for .Rdata in the cwd).
To set the R work directory like the current directory of the R script that I'm working, I always use a combination of the commands getwd() and setwd(), like this:
path <- getwd()
setwd(path)
or
setwd(getwd())
If you want learn more about it, see this article.
Cheers,
[]'s
To set working directory in R Studio:
Refer detailed slide deck with screen-shots here.
Using setwd(): windows users would need to replace backward slashes '' with forward slashes '/' or double backward slashes '\'
You can do the former using find & replace (Short-cut: Ctrl+F)
Another option: Go to Session --> set working directory --> choose working directory & browse the folder which you want to set as the working directory, click on open
Quickest method (my favorite) use the shortcut 'Ctr+Shift+H' (on windows system), browse the folder which you want to set as the working directory, click on open
To set a permanent working directory (when not in a project) in R Studio:
Refer my quick video on the same: https://youtu.be/hMjzO4bAi70
Go to Tools --> Global Options --> R General [Basic] --> Default Working Directory (when not in a project)
browse the folder which you want to set as the working directory, click on 'Apply' and 'OK'
However, the efficient & better way to organize your work is to create projects & use version control.
Put a shortcut for the R gui into your desired directory. Right-click and look at the shortcut properties. Delete the entry for "Start In" and click OK. When you launch the R gui from this shortcut the default directory will be the folder from which you have launched. Copy/paste this shortcut wherever you desire.
I asked this on Super User, but someone suggested that I take it here because there are many more R experts.
The question:
I have to keep navigating to my directory when I go to File > Change dir..., which is particularly annoying.
Does anyone know how to make R remember the previously used directory?
I keep all the code associated with a particular project in a file (or more often a series of files). The first line is usually
setwd(...)
which sets the directory.
Once a workspace has been saved in the desired directory, just start R by opening that workspace (rather than from the desktop or start menu). Then the directory is already set to where you want it.
I may not be answering your question, because it's a bit vague, but some thoughts:
You can store the location of 'my directory' in R's .GlobalEnv so that it starts there when you start R.
This article discuses how to have different working directories with corresponding different ".RData" files.
You could write a custom function that remembers the current directory before you set the new directory
cd <- function(x = "") {
logical (length = 0)
if (!is.logical(x)) {
cwd <- getwd()
Sys.setenv("R_OLDWD"=cwd)
setwd(x)
} else {
setwd(print(paste(Sys.getenv("R_OLDWD"))))
}
}
From the R for Windows FAQ:
The working directory is the directory from which Rgui or Rterm was launched, unless a shortcut was used when it is given by the `Start in' field of the shortcut's properties. You can find this from R code by the call getwd().
The home directory is set as follows: If environment variable R_USER is set, its value is used. Otherwise if environment variable HOME is set, its value is used. After those two user-controllable settings, R tries to find system-defined home directories. It first tries to use the Windows "personal" directory (typically C:\Documents and Settings\username\My Documents on Windows XP and C:\Users\username\Documents on Vista). If that fails, if both environment variables HOMEDRIVE and HOMEPATH are set (and they normally are), the value is ${HOMEDRIVE}${HOMEPATH}. If all of these fail, the current working directory is used.
You can find this from R code by Sys.getenv("R_USER").
This depends on the system that your using. There are a few tricks to use but if your looking to run R from a system menu and have it remember the directory the quick answer is no that won't happen. Linux is pretty easy just navigate to the directory in the terminal first and that will solve the problem. I have no idea about macs, But I can talk about windows extensively. First if you navigate to the directory and save your workspace once then you can use the saved .RData file to double click and restore your workspace including current directory. My personal, and biased opinion is to use an editor like Notepad++ with NppToR that way when you spawn a Rgui window you inherit the active directory from the current script. It also provides a menu command to adjust the working directory to the current script's directory.
Another point is that you can always set the working directory with the setwd("path/to/dir/") command inside any R session on any platform.
I use StatET and Eclipse as my R user interface. It automatically sets the working directory to the location of my project folder. workspace = ${project_loc}.
It also automatically loads any saved workspace, when starting R from a particular project.
On Windows, I put a file Rgui.bat from code.google.com/p/batchfiles in my project directory and use this to start R.