1 + 100[1] 101
3 + 5 * 2[1] 13
(3 + 5) * 2[1] 16
Adapted from Software Carpentry
Today we will learn to:
RStudio is a free, open-source IDE that makes R easier to use. It provides an editor, integrated console, and project management tools.
When RStudio opens, you’ll see:
R scripts (.R files) can be opened in the editor panel (top left).
You can work in two ways:
.R file.R file, use Ctrl+Return to run linesTo run the current line: click Run or press Ctrl+Return (Windows/Linux) or ⌘+Return (Mac).
To run a code block: select it and click Run.
R can perform arithmetic:
The [1] shown in output indicates the first element of a result.
Large/small numbers use scientific notation (e.g., 2e-4 means \(2 \times 10^{-4}\)):
Call functions with parentheses. Functions take arguments as inputs:
Use ?function_name to view help for any function.
Comparison operators:
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
Never use == to compare decimal numbers. Use all.equal() instead due to floating-point precision.
Assign values to variables using <-:
Variables appear in the Environment tab. Reassign at any time:
Valid names contain letters, numbers, underscores, and periods (must start with a letter or period). Conventions include periods.between.words, underscores_between_words, or camelCase. Be consistent.
Which of the following are valid R variable names?
Valid: min_height, max.height, .mass, MaxLength, celsius2kelvin
Invalid: _age (starts with underscore), min-length (hyphen not allowed), 2widths (starts with number)
R is vectorized - operations apply to entire vectors:
List all variables with ls():
Delete variables with rm():
To delete all variables: rm(list = ls())
When assigning function arguments by name, use = (not <-): rm(list = ls())
Extend R with packages. Common package commands:
<- to assign values to variables.ls() to list the variables in a program.rm() to delete objects in a program.install.packages() to install packages (libraries).