Chapter 1 Variables, Math, and Comparisons
1.1 Help
# Hi. This is a comment.
# If you know a function's name, but not how to use it:
?t.testYou can also click a function and press F1 to see the help page.
If you don’t know the exact name of a function or variable, you can type part of the name and press tab to autocomplete and see some info about it.
1.2 Assignment
a = 6
b = 8
c = 5.44
d = TRUE
e = "hello world"
e = 'hello world' # same as double quoteNote: No semicolon or “var” needed
You’ll sometimes see a <- 6 instead of a = 6. Just use =. Some people insist on using <-. They are silly.
1.3 Names with weird characters
R allows names to have a ., and it’s common in many built-in functions. For your own variables, avoid it if possible. If you want to have a space in a name, use an underscore (_) instead of being ridiculous.
To learn how to access object members, see the lists chapter.
this.is.a.variable.name = 1
better_name = 2You can use any weird character like a space in a variable name by surrounding the name with `. Avoid it if you can, but sometimes it’s necessary when you load data from a file.
`more than four (>4)` = 51.4 Console Output
Print a in the console
a#> [1] 6
The [1] is output because it is the first element in an array. For more info, see the arrays chapter.
Another option that’s useful inside functions, which don’t output most results
print(a)#> [1] 6
1.5 Math
Arithmetic
z = a + b
z = a - b
z = a * b
z = a / b
z = a %/% b # Integer division
z = a %% b # Note the double % for the modulo operator
z = a ^ b # exponent
1 + 2 - 3 * 4 / 5 ^ 6 # Please excuse my dear aunt, Sally#> [1] 2.999232
Note: There is no ++ or +=
Functions for floats
floor(4.82)#> [1] 4
ceiling(4.82)#> [1] 5
Rounding
round(4.4) # round down#> [1] 4
round(4.6) # round up#> [1] 5
round(4.5) # round to even (down)#> [1] 4
round(5.5) # round to even (up)#> [1] 6
Other basic math functions
sin(pi/2) + cos(0) # radians, not degrees#> [1] 2
log(exp(2)) # base e (like ln) is the default#> [1] 2
log(100, 10) # use base 10#> [1] 2
1.6 Comparisons
a == b#> [1] FALSE
a != b#> [1] TRUE
a > b#> [1] FALSE
a < b#> [1] TRUE
a >= b#> [1] FALSE
a <= b#> [1] TRUE
1.7 Boolean
TRUE & FALSE#> [1] FALSE
TRUE | FALSE#> [1] TRUE
!TRUE#> [1] FALSE
There’s & and &&. You usually want just &.