Assignment and type checking
name <- value
class(object) # "numeric" | "character" | "logical"
Every line of R starts here. Run class() whenever a calculation refuses to work or returns something odd.
- <-
- Assignment. A double equals is a comparison and stores nothing
- class()
- The object's type; a numeric column read as character is the commonest bug
Sequences
1:10 # both endpoints included
seq(from, to, by = step) # fixes the gap
seq(from, to, length.out=n) # fixes the count; gap = (to-from)/(n-1)
Building index vectors and axis values. Use by or length.out, never both.
- by
- Step size; may be negative to count down
- length.out
- How many values; the gap follows from n - 1
Selecting from a data frame
df$Col # one column, as a vector
df[rows, cols] # blank side means all of them
df[c("A","B")] # columns by name, returns a data frame
df[c(1, 6)] # columns by position
Whenever a function needs one column of numbers, use the dollar sign. When it needs a smaller table, use the no-comma bracket form.
- $
- Extracts one column as a vector, dropping the table
- [rows, cols]
- The comma separates the two axes; blank means all
Filtering and sorting
subset(df, cond1 & cond2) # AND: both must hold, narrows
subset(df, cond1 | cond2) # OR: at least one, widens
df[order(df$Col), ] # ascending, keep the trailing comma
df[order(-df$Col), ] # descending
Filtering rows and reordering a table. Use a double equals for equality tests.
- &
- AND; the result can never be larger than either condition alone
- |
- OR; |A or B| = |A| + |B| - |A and B|
- order()
- Returns positions, not values, so it goes in the row slot