Setting your working directory
Change your working directory with the
setwd() function, such as:
Note that the slashes always have to be forward slashes, even if you're on a Windows system. For Windows, the command might look something like:
If you are using RStudio, you can also use the menu to change your working directory under Session > Set Working Directory.
Installing and using packages
Chances are if you're going to be doing, well, pretty much anything in R, you're going to want to take advantage of some of the thousands of add-on packages available for R at CRAN, the Comprehensive R Archive Network. The command for installing a package is:
If you don't want to type the command, in RStudio there's a Packages tab in the lower-right window; click that and you'll see a button to "Install Packages." (There's also a menu command; the location varies depending on your operating system.)
To see which packages are already installed on your system, type:
Or in RStudio, go to the Packages tab in the lower-right window.
To use a package in your work once it's installed, load it with:
If you'd like to make sure your packages stay up to date, you can run:
That way, you get the latest versions for all your installed packages.
If you no longer need or want a package on your system, use the function:
If you want to find out more about a function, you can type a question mark followed by the function name -- one of the rare times parentheses are not required in R, like so:
This is a shortcut to the
help function, which does use parentheses:
However, I'm not sure why you'd want to use this as opposed to the shorter
If you already know what a function does and just want to see formats for using it properly, you can type:
You'll get a list with examples of the function being used, if there's one available. The arguments (
args) function just displays a list of a function's arguments:
If you want to search through R's help documentation for a specific term, you can use:
help.search("your search term")
That also has a shortcut:
??("my search term")
No parentheses are needed if the search term is a single word without spaces.
See the entire beginner's guide to R:
• Part 1: Introduction to R
• Part 2: Getting your data into R
• Part 3: Easy ways to do basic data analysis with R
• Part 4: Painless data visualization using R
• Part 5: Syntax quirks you'll want to know about R
• Part 6: Useful resources for R