6  R basics Part I

R as a calculator

R can serve as a simple calculator, for simple or more advanced operations.

Try the following commands

1+1
[1] 2

The output should be visible in your console.

Let’s try to calculate \(\frac{5 \times 4}{2}\) using R

(5 * 4)/2
[1] 10

The most common operations in R are listed below

Operation R symbol
addition +
subtraction -
multiplication *
division /
power operator ^

Practice

  • Search for the function to perform a square root

Solution 1

Creating Objects in R

We can create objects by simply assigning a value to it.

For instance

x = 2
class(x)
[1] "numeric"

I created a variable x and assigned to it the number 2. Therefore, x is a numeric variable.

x = "Giacomo"
class(x)
[1] "character"

Now, assigning "Giacomo" to x made it a character variable. A character variable will generally contains information in the form of letters. In Statistics, characters are generally called nominal variables.

To create objects in R we can use two symbols

  • The arrow symbol <-, such as x <- 2
  • The equality symbol =, such as x = 2

The two are equivalent.


You can name your object anything. The only rule is to not start by a number. See below

# Correct
Age <- 30
Name <- "Natalie"

# Incorrect, will generate an error
1Age = 30
2Name = "Natalie"

Practice

  • Assign the value 70 to a variable called y
  • Divide y by 2

Solution 2.

Arrays

We can store more than one value in a variable.

Let’s create a variable called df and let’s assign five values to it.

df <- c(22, 27, 30, 36, 40)
df
[1] 22 27 30 36 40

We used the assignment operator <- to allocate the values to df. We used the parentheses () separated by a comma , for assigning multiple values, but also c to start the list.

We now can perform mathematical operations on this array (df)

For instance, let’s calculate the average

mean(df)
[1] 31

We have used the R function called mean() to calculate the average of this list.

Practice

Create an array called df_birthday with the year of birth of five people you know.

  • Compute the mean and standard-deviation for df_birthday
  • Compute the minimum and maximum values for df_birthday

If you do not know the name of a function, simply google it!

Solution 3.


  1. Solution.

    sqrt()
    ↩︎
  2. Solution.

    y = 70
    y/2
    ↩︎
  3. Solution for five people I know

    df_birthday = c(1987, 1990, 1983, 1999, 2000)
    mean(df_birthday)
    sd(df_birthday)
    min(df_birthday)
    max(df_birthday)
    ↩︎