An important lesson you should learn early on is that there are multiple ways to do things in R. For example, to generate the first five integers we note that 1:5
and seq(1,5)
return the same result.
There are also multiple ways to access variables in a data frame. For example we can use the square brackets [[
instead of the accessor $
.
If you instead try to access a column with just one bracket,
murders["population"]
R returns a subset of the original data frame containing just this column. This new object will be of class data.frame
rather than a vector. To access the column itself you need to use either the $
accessor or the double square brackets [[
.
Parentheses, in contrast, are mainly used alongside functions to indicate what argument the function should be doing something to. For example, when we did class(p)
in the last question, we wanted the function class
to do something related to the argument p
.
This is an example of how R can be a bit idiosyncratic sometimes. It is very common to find it confusing at first.
# Load the data
library(dslabs)
data(murders)
# We extract the population like this:
p <- murders$population
# This is how we do the same with the square brackets:
o <- murders[["population"]]
# We can confirm these two are the same
identical(o, p)
#> [1] TRUE
Use the accessor $
to assign the state abbreviations to a
(as in the previous question). Use the square brackets [[
ot assign them to b
. Afterwards, use the identical
function to determine if a
and b
are equal.
NOTE
Do not forget to first load the data as in the previous exercises!