5. We can run
individual
commands of
code by entering
them into the
console.
R prints out the
results of running
the code.
This is like using a
calculator.
6. We can run a command
or selection of
commands in the
source.
You can click the Run
button or use CTRL +
Enter or the Mac
equivalent.
This sends the line to
console. The console
prints the result.
7. Recap: R as a calculator
• We run R commands.
• The result of that command is printed to the console.
• But that’s pretty limited.
• We would like to save our results and reuse them again.
9. Assignment
x <- 100
• “Assign the value 100 to the variable x.”
• “x gets 100”
• The arrow <- is putting value into the variable.
x <- 10
• If we assigned 100 to x earlier, then this assignment will overwrite that value.
x = 100
This will do the same thing, but = has a different but very similar meaning in some other
contexts so we prefer <- for assignment. This is generally what other people do too.
10. Assignment is a
command. We run it. It
shows up in the
console.
It does not print a
result, but it does
change the
environment.
We see the change in
the environment pane.
We can reuse the
variable in later
commands.
12. Lines that begin with # are
comments. They can be run but
they are ignored.
They are used for documenting
code, taking notes, etc.
They are also used for disabling
code. You probably have received
a script from me with lines like
# install.packages(“dplyr”)
library(dplyr)
where I disabled a line that needs
to be run just one.
13. library(tidyverse)
library(palmerpenguins)
penguins <- penguins %>%
select(species, flipper_length_mm, bill_length_mm)
# There are three species
penguins %>% count(species)
#> # A tibble: 3 x 2
#> species n
#> <fct> <int>
#> 1 Adelie 152
#> 2 Chinstrap 68
#> 3 Gentoo 124
One other convention for
comments (that I use and that
you will often see) is that
comments beginning with #> or
## will be printed after code to
show the results that were
printed to the console.
15. Assignments (commands with <-)
don’t print their results. But
sometimes you see something
printed to the console when you
perform and assignment.
These will be informational
messages, warnings, or errors.
In this case, the summarise()
function is telling me that it
removed the species group
because it simplified the data to
just one row per group (species).
16. This is typical for what I write.
I build up datasets and change
them and store the results
with assignment lines (lines 4-
5 and 10-17)
Otherwise, I print out the data
to look at it (8 and 17).
The only way to change the
data and re-use that changed
data in later commands is with
assignment. Otherwise, R is
just a calculator, printing a
one-off calculation.