Chapter 1 R Basics (FQA)

At its most basic, R can be used to perform standard mathematical operations, such as addition, subtraction, multiplication, etc.

## [1] 4

1.1 Variables

The assignment operator (<-) is used to store a given value into a variable. The code below creates a variable called x that stores the value 2.

Note that assigning the value 2 to the variable x does not produce any output; if we want to check the contents of x, we need to run a line with x by itself.

## [1] 2

Variables in R are case sensitive! The code above would not work if x were capitalized.

1.1.1 Atomic Vectors

In R, atomic vectors store one or more values of the same data type. We can create an atomic vector using the c() function, which stands for combine:

##  [1]  5  9  2  3  4  6  7  0  8 12  2  9

We can extract specific values from the atomic vector using the bracket notation ([]). The code below extracts the first three values in v1. Note that inside the brackets, we specify the indexes of the values we want (1, 2, and 3) with another atomic vector.

## [1] 5 9 2

1.2 Functions

Like Excel or any other statistical package you may have used in the past, R has many built-in functions. Function arguments are specified within parantheses. To look up the syntax for a given function, start by searching for it at rdocumentation.org.

Here are some basic functions we can apply to our vector v1:

  • mean()
  • median()
  • sd()
  • sum()
  • length()

For example:

## [1] 5.583333
## [1] 67
## [1] 12
## Warning: package 'knitr' was built under R version 4.0.5