Every lesson assumes you can run code and look things up in R's built-in help.
R is an interactive environment first. Start R in a terminal (or open RStudio or Positron, the popular IDEs) and type expressions at the > prompt; the value is printed automatically. Save code in a .R file and run it with source("file.R") from the console or Rscript file.R from the shell.
Assignment is conventionally <-: x <- 42. = also works at the top level, but in function calls = names an argument, so style guides reserve it for that. Names are case sensitive and may contain dots and underscores (my.data, my_data).
- A comment starts with
#. print(x)prints explicitly. You need it inside functions, loops and files run withsource(), because auto-printing only happens for top-level expressions (typed at the console or run byRscript).cat()prints without quotes or[1]index prefixes.
The [1] at the start of output means the line starts with element 1: everything in R is a vector, even a single number.
Help is built in. ?mean opens the documentation for mean, ??regression searches all help pages, and example(mean) runs the examples. Packages extend R: install.packages("dplyr") installs one from CRAN once, and library(dplyr) attaches it in each session.
Example
# run with: Rscript hello.R
x <- 42
y = 8 # works, but prefer <-
x + y #> [1] 50 (top level: auto-printed)
print(x + y) #> [1] 50
cat("x is", x, "\n") #> x is 42
print(1:12 * 10)
#> [1] 10 20 30 40 50 60 70 80 90 100 110 120
print(R.version.string) #> [1] "R version 4.x.y (...)"
print(class(x)) #> [1] "numeric"Remember
- Assign with
<-; use=for function arguments print()is needed inside functions, loops and sourced files?nameopens help;install.packagesonce,libraryevery session
Watch out for
- Expecting values to print inside a for loop or a function without calling print().