9  Syntax, Calculations, Common Commands, and Variables

9.1 Basic R syntax and calculations

1 + 1 # Simple arithmetic
[1] 2


2 + 3 * 4 # Operators
[1] 14


3^2 # Exponentiation
[1] 9

9.2 Predefined basic mathematical functions

Try these!

exp(1)
[1] 2.718282


sqrt(10)
[1] 3.162278


pi 
[1] 3.141593


Is this a common or natural logarithm?

log(3)
[1] 1.098612

9.3 Add comments

In R, we use the # symbol to make comments. It is best to return and continue if your comments are lengthy (rather than one long line).

# In R, we use the # symbol to make comments.
# It is best to return and continue if your
# comments are lengthy (rather than one long 
# line). We will continue to learn more about
# basic R syntax throughout this introduction
# on R, including the assignment operator and 
# defining variables. 

9.4 The assignment operator

In RStudio the keyboard shortcut for the assignment operator is Alt - (Windows) or Option + - (Mac).

Why should we use the assignment operator <- instead of equals = ?

  • Historical convention
  • While both <- and = can work, adhering to the convention helps avoid ambiguity and makes the code more consistent and readable.
  • In R, the equals sign = is also used for specifying arguments in function calls. For example, in the function call mean(x, na.rm = TRUE), the = is used to set the na.rm argument to TRUE. To avoid confusion between assignment and argument specification, it’s clearer to use <- for assignment.
  • Other pitfalls

9.5 Creating variables

What are the rules for creating variable names?

  • Must start with a letter.
  • The rest of the name can include letters, numbers, periods, and underscores.
  • Variable names are case sensitive ‘age’ vs ‘Age’ vs ‘AGE’ are all different
  • Avoid using the names of base functions, for example pi.
  • Others?

Try these!

x <- 3
y <- 5
z <- 6
x * y * z


# Variable names can include variable names and periods:
This.Year <- 2025

9.6 Modulo in R?

5 %% 2
[1] 1


20 %% 6
[1] 2


42 %% 5
[1] 2

9.7 Whitespace

R generally ignores whitespace, such as spaces and tabs, making it flexible with formatting. Note that proper use of whitespace improves code readability. For example:

x<-10 
x <- 10

9.8 The cat() function

Should I use print statements?

You may use print statements for your reports, but for your own coding, we generally do not use print statements as they can become time consuming and may clutter the source code.

An alternative is the cat() function which can be used to concatenate and print text. Compare the following outputs:

x <- 10
print(x)
[1] 10
cat(x)
10

The cat() function more formally:

x <- 10
cat("The value of x is:", x," \nThis is the next line.")
The value of x is: 10  
This is the next line.

The slash and n tells R to move down to a new line.

9.9 Where is the working directory?

#getwd()

To set your working directory:

#setwd("C:/Users/llmur/Desktop/ADS 2288F Programming Skills/_Lectures/_Slides/R Programming I Introduction")
  • Run getwd() again to verify!

  • Alternatively, you can go to “Session” –> “Set Working Directory.”

9.10 Helpful tips along the way

  • Double check your spellings (case sensitive), brackets and commas if you receive an error.
  • If the “+” operator in the console won’t go away you’re likely missing a closing bracket or quote. Hit the “Esc” key and try again.
  • Have you ran your code? Check the console.
  • Move the cursor to the console and use the up arrow to view previous code again. Hit “Enter” to run previous code again.
  • Stop and pause just before bracket at the end of a function to view its description and arguments.
  • You can change settings with global options.

9.11 Reflection questions

  1. Why is it recommended to use <- instead of = for assignment in R?

  2. When using a function like exp() or sqrt(), how can you find out what other arguments it accepts?

  3. How does being case-sensitive influence how you choose your variable names in R?

  4. Why might clean formatting and consistent whitespace matter, even if R ignores it when executing the code?

  5. In what situations might you prefer cat() over print()? What are the advantages or disadvantages?

  6. Why is it important to understand your working directory in RStudio?

  7. How can setting your working directory incorrectly affect your workflow?

  8. What are some common mistakes that cause error messages in R? How would you go about fixing them?

9.12 Exercises

  1. What is R used for, and how does it compare to Python?

  2. What is a built-in function in R? Give two examples.

  3. Which of the following are valid variable names in R?

my_var
2value
.score
%data
  1. Create a new variable a and assign it the result of 10 %% 3. What does this operator do?

  2. You want to check where R is currently reading/writing files and then change it to your “Documents” folder. What two lines of code do you use?

  3. You want to create a variable called summary but get strange errors when running summary functions. Why?

  4. Why is whitespace important in R scripts?

  5. What is the problem with this code?

score <- 80  
passing <- 70  
score => passing
  1. Write R code that stores your name in a variable and then prints a message like “Hello, your_name!” using cat().

  2. Compare these two statements. How are they different?

print("Result:", 6 + 2)
cat("Result:", 6 + 2)
  1. This code runs, but something is off. What’s two things are wrong, and how do you fix them?
print("The result is:" 4 + 4)
  1. Why does this produce an error?
print("The result is:", 10 + 5)  
  1. You created a variable z <- 6. How can you test if R recognizes it without printing it manually?

  2. Fatima runs the following code:

x <- 10
x == 10

She sees [1] TRUE as the output. Why doesn’t this assign anything to x?

  1. Lin types:
5 + "apple"

What error does R return, and why?

  1. Karl runs this code:
a <- 4
b <- 2
a > b

What does it return, and how can he interpret it?

  1. Try this code. What is the output and why?
x <- "5"
x + 2
  1. What does this code return and why?
x <- 5  
y <- "5"  
x == y  
  1. Using the the variables a <- 3 and b <- 4, create a code that will display “Sum: 7 Product: 12”. HINT: use a+b and a*b

  2. Write a line that adds 3 and 4, divides the result by 2, and prints it.

  3. Create a line of code that prints the result of 5 squared and states what operation you did.

  4. Write a line of code that calculates the natural log of 100 and rounds the result to 2 decimal places. HINT: Use the built-in function round()

  5. Create a line of code that prints the value of pi with 3 decimal places.

  6. What happens if you run sqrt(-1) in R?

  7. What do “\n” and “\t” do in R? Give an example.

  8. What code produces this output? Indented Newline

    Indented
Newline 
  1. Ryan runs the following code but doesn’t get a new line between the two printouts. Why?
cat("Good morning!")  
cat("Welcome back!")  
  1. Use cat() to print this poem with the exact formatting shown (including indents and line breaks):
Jack be nimble,  
    Jack be quick,  
Jack jumped over  
    The candlestick.
  1. Logan writes:
cat("Result:\n", 3^2, "\n", "Squared")

But the output isn’t formatted like he expected. Rewrite the line so it prints:

Result:
9 squared
  1. Identify the four major issues with the following code:
a<-10
b<-3  
c=a%%b
cat(c)
  1. The following loop never stops. What should you press in RStudio?
while(TRUE) {
  print("Oops")
}
  1. Identify four issues in this code:
x=5
Y <- 2
print("Sum is:", x + y)