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. R has three: [, [[ and $, but why?

bracket accessors visualisation

A visual representation of the bracket accessors made by Hadley Wickham

Subset with [

When you take a subset of an object the returned object will have the exact same datatype as the original object. The subset of a vector, list and dataframe are respectively a vector, list and dataframe. You can subset variables in two ways:

Extract one variable with [[

When you extract one variable it wont have the same datatype as the original object. This is because are unpacking the object. For example: When you extract a variable from a dataframe you get a vector with the column data. You can extract variables in two ways:

Extract one named variable with $

In the case where you want extract one named variable you can use the $ operator instead of [[. The only difference is that this method is six times shorter ($ vs [[""]]), this operator doesn’t expect a numeric or character. Instead you can acces the variable the the same way as a normal variable.

murders$population

Exercise

  1. Create a dataframe abb_df containing one column named “abb”. This column should contain the abbreviations column from the murders dataset. To do this you will have to extract the abbreviations column and then create a new dataframe using the data.frame function. Read the help page help(data.frame) to see how you can specify column names.

  2. Use the accessor $ to extract the state abbreviations variable. Assign the result to a.

  3. Use the square brackets [[ to extract the state abbreviations variable. Assign the result to b.

  4. Use the identical function to determine if a and b are equal.


NOTE We have already loaded in the murders dataframe for you.