Session Ready
Exercise

Multiple ways to access variables

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 $. Example code is included in the editor.

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.

Instructions
100 XP
  • Use the square brackets [[ to extract the state abbreviations and assign them to the object b.
  • Then use the identical function to determine if a, as defined in the previous exercises, and b are the same.