One of the most basic ways to use R is as a calculator. We can enter many math functions directly into the R Console. We will start to look at the various ways in which we can use R.
R can handle most simple types of math operators.
Operator | Description |
---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
^ or ** |
Exponentiation |
For example:
# Addition
5+4
## [1] 9
# Subtraction
124 - 26.82
## [1] 97.18
# Multiplication
5*4
## [1] 20
# Division
35/8
## [1] 4.375
We can also use many other math functions. All of these are included in base R without any extra packages.
# Exponentials
3^(1/2)
## [1] 1.732051
# Exponential Function
exp(1.5)
## [1] 4.481689
# Log base e
log(4.481689)
## [1] 1.5
# Log base 10
log10(1000)
## [1] 3
Another important feature of R is the ability to use logic. This is not unique to R as all programming languages can do this, but it will be extremely useful when working with data.
Operator | Description |
---|---|
< |
Less Than |
> |
Greater Than |
<= |
Less Than or Equal To |
>= |
Greater Than or Equal To |
== |
Exactly Equal To |
!= |
Not Equal To |
!a |
Not a |
a&b |
a AND b |
We can then see an example of this:
a <- c(1:12)
If we wanted to know where a>9 or where a<4 we would expect to see the values: 1 2 3 10 11 12.
a
## [1] 1 2 3 4 5 6 7 8 9 10 11 12
a>9
## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
## [12] TRUE
We can see that what R gives is are Boolean values as to whether or not each element of a
is greater than 9. Similarly:
a<4
## [1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [12] FALSE
One simple thing we might try is to just combine these 2 values into a conditional
a>9 | a<4
## [1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
## [12] TRUE
This again just gives us Booleans and not necessarily the values that we were hoping to see. We use this to index a
in the following manner
a[a>9 | a<4]
## [1] 1 2 3 10 11 12
We will look at indexing with much further detail as we move through this course.
There are other operators that we will use that are not necesssarily mathematical in nature. Each one of them is crucial for the use of R.
Description | R Symbol | Example |
---|---|---|
Comment | # | # This is a comment |
Assignment | <- |
x <- 5 |
Assignment | -> |
5 -> x |
Assigment | = |
x = 5 |
Concatenation operator | c | c(1,2,4) |
Modular | %% | 25 %% 6 |
Sequence from a to b by h | seq | seq(a,b,h) |
Sequence Operator | : | 0:3 |
We also have access to a wide variety of mathematical functions that are already built into R.
Description | R Symbol |
---|---|
Square Root | sqrt |
floor(x) |
floor |
\ceil(x) |
ceiling |
Logarithm | log |
Exponential function, e^x |
exp |
Factorial, ! |
factorial |