Evaluating R expressions

First, let’s evaluate some R expressions in the console. The simplest expressions are numerics and strings:

42
## [1] 42
"Hello"
## [1] "Hello"

R simply repeats these values back at us.

A more complex expression is something like 42 + 43. Let’s try this:

42 + 43
## [1] 85

This is more interesting – R evaluated the expression and gave us the value back. We can evaluate more complex expressions too:

(45 - 43) ** 3
## [1] 8

We can also evaluate logical values

5 == (4 + 1)
## [1] TRUE
7 > (5 - 1)
## [1] TRUE

Note that to compare to values, we need to use two equal signs: ==. The resultant value is True or False (in R, you can also use T and F). It’s a value just like numeric values and character values are values. It is called a logical value.

Printing to the console

We can also print the values of expressions to the console. This is subtly different from just entering expressions and getting their values back:

cat(42 + 1)
## 43
cat("Hello")
## Hello

Note that Hello was printed without quotes – that’s because we are not just printing the value of "Hello" back, we are just printing “Hello.” (As an aside, in the Philosophy of Language, this is called “disquotation.”)

We can print several values like so:

cat("Hello", 123, "hi", 5 + 1)
## Hello 123 hi 6

Variables

Variables in R store values. Here is a simple example:

exam <- 80
cat(exam)
## 80

The variable exam stores 80 after we execute exam <- 80. We can read this as “store 80 in exam”. Note that cat(exam) and cat("exam") are different (exercise: explain how they are different).

Let’s now look at a larger program

exam <- 80
harvard.adj <- 10
exam <- exam + harvard.adj
cat("Your exam grade is", exam)
## Your exam grade is 90

Note how R variables are different from the variables you’re used to in math: in math, you cannot say x = x + y (or rather, you can, but this will just mean that y = 0). In R, the similar expression exam <- exam + harvard.adj means * Compute exam + harvard.adj * Store the resultant value back in the variable exam

Conditionals

Here is how we can compute and output the absolute value of any number

n <- 125
if(n >= 0){
  cat(n)
} else {
  cat(-n)
} 
## 125

(Note that we could assign any numeric value to n, not just 125).

The if statement above works by first evaluating n >= 0. If the value is True, cat(n) is excuted (the statement(s) inside the if-clause). Otherwise, the statment inside the else-clause is executed. That means that for positive numbers, we’ll print the number itself. For negative numbers, we’ll print the positive number with the same aboslute value. So in either case, we’ll print the absolute value of n.

Here is another example:

exam.grade <- 45
if(exam.grade == 98){
  cat("I am reasonably happy")
}else if(exam.grade >= 60){
  cat("Hooray! I passed!")
  cat("But I could do better")
}else{
  cat("Alas")
}
## Alas

This demonstrates the fuller capabilities of the if-statement. Here is what happens: we evaluate the conditions top-to-bottom, so, we evaluate, in order,

If a condition is true, we execute the statements inside the corresponding clause, and don’t execute anything else. If a condition is false, we move on to the next condition. If none of the conditions are true, we execute the statements inside the else clause.

Note that it’s important in which order we set the conditions. Consider:

my.score <- 82
if(my.score >= 98){
  cat("Hooray!")
}else if(my.score >= 95){
  cat("OK!")
}else{
  cat("Alas!")
}
## Alas!
my.score <- 98
if(my.score >= 95){
  cat("OK!")
}else if(my.score >= 98){
  cat("Hooray!")
}else{
  cat("Alas!")
}
## OK!

In the second piece of code, we’ll never print Hooray!, since for any score above or at 95, we’ll just always print "OK".

Functions

We can call (i.e., use) R functions similarly to how we do it in algebra. For example, here is how we can use the function abs.

abs(-6)
## [1] 6
abs(50)
## [1] 50

Let us now create our own function, named my.abs, which will do the same thing as abs – compute the absolute number of the input.

my.abs  <- function(x){
  if(x >= 0){
    x
  }else{
    -x
  }
}

The variable x is a “dummy variable” (think \(f(x) = x^2\) or \(g(y) = y^2\), which are exactly the same, since the names of the functions and the dummy variables don’t matter). When we call the function, we assign -5 (or 10, or anything else) to x. The value of the function is determined by what’s inside the return statement.

Let’s try to use my.abs:

my.abs(-20)
## [1] 20
my.abs(123)
## [1] 123

We can use “scratch variables” inside functions to store results of intermediate computations:

my.abs.mod  <- function(x){
  y <- 2 * x
  if(y >= 0){
    y/2
  }else{
    -y/2
  }
}

my.abs.mod does the same thing as my.abs – we just computed y for demonstration purposes. The last value in the function is the value of the function.