1. Basic Syntax

In this lesson we will review the basic syntax in R, including defining several common operators.

In this lesson we will review some of the basic syntax in R, including the following common operators:

Syntax

Syntax in computer programming is a set of rules that defines the structure of a language, similar to how we have rules for grammar and spelling. If you write a sentence with incorrect spelling or grammar, the sentence may not make sense. If you write code without proper syntax, the code won’t be able to run and you’ll get an error message.

Example

To run the line of code below (aka R chunk) you can either push the green arrow pointing to the right or click on the line of code and push ctrl+enter (windows) or cmd+enter (mac).

print("hello world")
[1] "hello world"
Print("hello world")
Error in Print("hello world"): could not find function "Print"

Operators

Assignment Operator

Before you run the R chunk below, click on the Environment pane (usually located in the top right corner of RStudio). Watch what happens when you run the code below. If you’re unfamiliar with the Environment tab, I recommend watching my tutorial on Introduction to R.

x <- 10
x
[1] 10
y <- 25
y
[1] 25
z <- 100
z
[1] 100

Greater or Less than Operators

x > y
[1] FALSE
x < y 
[1] TRUE

Equality Operators

x == y 
[1] FALSE
x # x is still 10
[1] 10

Note here, we have a # followed by some text. A # in R indicates a comment. Any text that follows a # will not be evaluated. This is a great way to leave notes or comments for yourself.

x = y # remember, this could also be x <- y
x # x is now 25
[1] 25
x <- 10
x != y 
[1] TRUE

The And Operator

z > 50 & z < 200 
[1] TRUE
z > 50 & z > 200
[1] FALSE

The Or Operator

z > 50 | z > 200
[1] TRUE

Summary

In this lesson we learned about syntax in R and some of the most common operators (<-, >, <, ==, !=, !=, &, |).

We also learned a few useful tips, including how to run R chunks and how to leave comments using the #.

Exercises

In this exercise, we’ll compare the heights (in inches) of some amazing female artists: Jennifer Lopez, Taylor Swift, and Miley Cyrus.

  1. Create three variables with each woman’s respective height (Jennifer = 64.57, Taylor = 70.87, Miley = 64.96). Save your three variables as jennifer, taylor, and miley.

Remember to use the assignment operator and make sure to run each line of code (or the entire code chunk) to make sure we save the variables to the environment.

  1. Is Miley shorter than Taylor? Write 1 line of code that will return the answer as either TRUE of FALSE.
  1. Are Miley and Jennifer the same heights?
  1. Is Miley taller than both Jennifer and Taylor?
  1. Is Miley taller than either Jennifer or Taylor?

THE END 🎉