Chapter 7 R Syntax
Frustration is natural when you start programming in R. R is a stickler for punctuation, and even one character out of place will cause it to complain. But while you should expect to be a little frustrated, take comfort in that it is both typical and temporary: it happens to everyone, and the only way to get over it is to keep trying.
To understand computations in R, two slogans are helpful:
- Everything that exists is an object.
- Everything that happens is a function call.
7.1.1 Arithmetic operators
In its most basic form, R can be used as a simple calculator. Consider the following arithmetic operators:
|^ or **||exponentiation|
|x %% y||modulus (remainder)|
But when we do this, none of our results are saved for later use.
7.1.2 Assigning Variables
An essential part of programming is creating objects (or variables).1 Variables are names for values.
A variable is created when a value is assigned to it. We do that with
<- is called the assignment operator. It assigns values on the right to objects on the left, like this:
So, after executing
x <- 3, the value of
3. The arrow can be read as 3 goes into
NB: Do not use
= for assignments. It will work in some contexts, but it will cause confusion later. There will be other scenarios where you will use
= - we will discuss these later on.
We can use variables in calculations just as if they were values.
Inspect objects to display values.
In R, the contents of an object can be printed by simply executing the object name.
7.1.3 Variable Names
Object names can only contain letters, numbers,
You want your object names to be descriptive.
x is not a good variable name (sorry!). You will also need a convention for multiple words. I recommend snake_case, where you separate lowercase words with
Let’s make an assignment using snake_case:
And let’s try to inspect it:
R is case-sensitive!
Challenge 1: Making and printing variables.
Make 3 variables: name (with your full name), city (where you were born), and year (when you were born).
Challenge 2: Swapping values.
Draw a table showing the values of the variables in this program after each statement is executed.
In simple terms, what do the last three lines of this program do?
Challenge 3: Predicting values.
What is the final value of
position in the program below? Try to predict the value without running the program, then check your prediction.
R has a large collection of built-in functions that helps us do things. When we use a function, we say we are calling a function.
Here are some helpful built-in functions:
An argument is a value that is passed into a function. Every function returns a result.
Let’s try using
seq(), which makes regular sequences of numbers. While we are at it, we will learn more helpful features of RStudio.
se and hit TAB. A popup shows you possible completions. Specify
seq() by typing more (a
q) to disambiguate, or by using ↑/↓ arrows to select. Notice the floating tooltip that pops up, reminding you of the function’s arguments and purpose.
Press TAB once more when you have selected the function you want. RStudio will add matching opening (
() and closing (
)) parentheses for you. Type the arguments
1, 10 and hit return.
How many arguments did we pass into the
7.2.2 Store Function Output
Notice that, when we called the
seq function, nothing changed in our environment. That is because we did not save our results to an object. Let’s try it again by assigning a variable:
7.2.3 Argument Restrictions and Defaults
Let’s use another function, called
round must be given at least one argument. Moreover, it must be given things that can be meaningfully rounded.
Functions may have default values for some arguments.
round will round off any number to zero decimal places. But we can specify the number of decimal places we want.
7.2.4 Documentation and Help Files
How do we know what kinds of arguments to pass into a function? Every built-in function comes with documentation.
?+ object opens a help page for that specific object.
??+ object searches help pages containing the name of the object.
All help files are structured the same way:
- The Arguments section tells us exactly what kind of information we can pass into a function.
- The Value section explains what the output of the function is.
- The Examples section contains real examples of the function in use.
Challenge 1: What Happens When
Explain, in simple terms, the order of operations in the following program: When does the addition happen, when does the subtraction happen, when is each function called, etc.
What is the final value of
7.3 Data Types
Every value in a program has a specific type. In R, those types are called “classes”, and there are 4 of them:
- Character (text or “string”).
- Numeric (integer or decimal).
- Integer (just integer).
- Logical (TRUE or FALSE booleans).
|2 (Must add a
7.3.1 What Is that Type?
R is dynamically typed, meaning that it “guesses” what class a value is. Every piece of information in R has a type!
Use the built-in function
class() to find out what type a value has.
This works on variables as well. But remember: the value has the type — the variable is just a label.
A value’s class determines what the program can do to it.
We just learned we cannot subtract numbers and strings. Instead, use
as. + name of class as a function to convert a value to a specified type.
This is called
coercion. Here is another example:
What difference did you notice?
7.3.3 Other Objects
There are a few other “odd ball” types in R:
NA are missing values.
Missing values are specified with
NA will always be coerced to the correct type if used inside
Challenge 1: Making and Coercing Variables
- Make a variable
yearand assign it as the year you were born.
- Coerce that variable to a string and assign it to a new variable
- Someone in your class says they were born in 2001. Really? Really. Find out what your age difference is, using only
7.4 Boolean Expressions
Boolean expressions are logical statements that are either true or false. For our purposes, we will often use Boolean expressions to compare quantities. For instance, the Boolean expression
1 < 2 is true, whereas the Boolean expression
1 > 2 is false.
When you type a Boolean expression in R, R will output
TRUE if the expression is true and
FALSE if the expression is false.
7.4.1 Boolean Operators
||less than or equal to|
||greater than or equal to|
||exactly equal to|
||not equal to|
||is an item of a set|
Note that we use a double equal sign
== to check whether two values are equal. Typing
a = b would set the value of
a equal to the value of
Here are some examples of Boolean expressions in action:
7.4.2 Logical Operators
In practice, we often use two or more conditions to decide what to do. To combine different conditions, there are three logical operators:
& is similar to AND in English, that is,
x & y is true only if both
y are true. Second, is similar to OR in English, that is, A || B is false only if both
y are false. Third,
! is similar to NOT in English, that is,
!x is true only if
x is false.
Different operator take different precendence. It is always a good practice to use brackets to control operation ordering.
7.4.3 Boolean Vectors
The nice thing about R is that you can use these comparison operators also on vectors. As with many expressions in R, the Boolean expressions discussed above are all vectorized. We will learn more about vectors and vectorization later in this class, but here is a quick example:
This command tests for every element of the vector if the condition stated by the comparison operator is
7.4.4 Boolean Vectors in Action
Boolean vectors are partially what makes R so magical. Check out the example below and examine each line. We will cover subsetting operations later, but pay attention to the work of boolean expressions and logical operators.
# An example x <- c(1:10) x[(x>8) | (x<5)] #>  1 2 3 4 9 10 # How it works x <- c(1:10) x #>  1 2 3 4 5 6 7 8 9 10 x > 8 #>  FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE x < 5 #>  TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE x > 8 | x < 5 #>  TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE x[c(T,T,T,T,F,F,F,F,T,T)] #>  1 2 3 4 9 10
In the partially written code below,
vector_2 each contain 10 values. Using the fact that Boolean expressions are vectorized, write code that outputs:
- A vector of length 10 such that element
iof this vector equals
vector_1[i]is less than
- The number of times that element
vector_1is less than element
vector_2, using the
Technically, objects and variables are different things, but we will use the two interchangeably for now.↩︎