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:
<-
assignment operator>
greater than operator<
less than operator==
equality operator!=
inequality operator&
and operator|
or operatorSyntax 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.
In this example, we are trying to print the following famous coding statement: “hello world”.
In this first R chunk, we can see how to successfully print “hello world”.
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"
<-
.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
>
is the greater than operator.<
is the less than operator.x > y
[1] FALSE
x < y
[1] TRUE
==
is the equal-to operator.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.
==
and =
.x = y # remember, this could also be x <- y
x # x is now 25
[1] 25
x <- 10
!=
is the not-equal-to operator (opposite of ==).x != y
[1] TRUE
&
is the “and” operator.z > 50 & z < 200
[1] TRUE
z > 50 & z > 200
[1] FALSE
|
is the “or” operator.|
operator instead of an &
operator.z > 50 | z > 200
[1] TRUE
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 #.
In this exercise, we’ll compare the heights (in inches) of some amazing female artists: Jennifer Lopez, Taylor Swift, and Miley Cyrus.
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.
TRUE
of FALSE
.