Introduction to R

Hello again!

Last time we installed R-Studio. Now we will look at some useful commands and syntax. You can use R directly from the terminal or from R-Studio. To use R from the terminal type “sudo R” at the terminal prompt.

Sudo R

Sudo R

R loads in interactive mode. You will be presented by the prompt >. Each input expression is evaluated immediately and the answer is returned. For example:

R Example

R Example

The value [1] next to the result indicates that the data displayed starts from the first element. In other words, 5 is the first element in the result. This is more intuitive when we see vectors and other large data.

Some important key notes:

  1. Unfortunately there is no standard naming convention. Google provides a very useful and concise guide: https://google.github.io/styleguide/Rguide.xml.
  2. R is case sensitive, thus MyFunction and myFunction are two different functions.
  3. Different R interpreters may have slightly different functions and modules. Thus it is not guaranteed that an R script running on one R interpreter works on a different interpreter.
  4. R is powerful and at times this can be dangerous! Always read the help and understand what the function does. For example, Let v1 be the vector [1, 2, 3] and v2 be the vector [1, 2, 3, 4, 5, 6]. Since, v1 and v2 do not have the same size, we cannot add them together. However, you can do so with R. In fact:

    R Example 2

    R Example 2


    What happened here? R recycled v1 so that its length becomes the same as v2 and computed the sum. In general, if two vectors are of unequal length, the shorter one will be recycled in order to match the longer vector. This is known as the Recycling Rule.

Some Basics:

<- is the assignment operator
# This is a comment
c() combines arguments in a list or vector
help() provides general help
help(x) provides help on x
help.search("x") search for topics that include the word x
example(x) provides examples for the function x

Simple Arithmetic:

# Addition: 2 + 7
# Subtraction: 21 - 3
# Multiplication: 18 * 19
# Division: 45 / 4
# Power: 2 ^ 5
# Modulus: 85 %% 6
# Integer Division: 85 %/% 6
# Constants: 2 * pi
# Infinite: 1 / 0
# Not a number: (-8)^(1/3)  # note that R follows the IEC 60559
# Complex numbers: (2 + 3i) + 7

Logarithms:

# Natural log: log(10)
# Log to base 10: log10(10)
# Log to base 2: log2(2)
# Log to base x: logb(10, base = 3)
# Exponent: exp(1)

Trigonometric functions:

# cos(pi)
# sin(2 * pi)

Using variables:

x <- 3
y <- 2
x + y