Introduction
Key elements of the visualization process
Environment - the R Language
19. Extracting a whole column

Instruction

The last thing that you need to know about data frames is the $ operator. This operator lets us extract one specific column (as a vector) from the data frame. Let's say you wanted to extract the age column from the family data frame. Here's how it would look:

family$age

This will return a vector with all the values in the age column. This approach to extracting columns allows us to change their values using the just one function. Remember, many functions work with vectors, simultaneously performing the same operation on all the values in the vector. Since we've extracted the column as a vector, we can work with it as a vector. We can then change all the column values at once by assigning the transformed version to the original column.

Suppose you want to add ten years to every age in the family dataset's age column. We would write:

family$age <- family$age + 10

This will automatically extract the column age as a vector, add 10 to all of its values, and then save the result to the original data frame. This gives us the family data frame with changed ages:

   name     sex  age    marital_status
1  Anne      M    33           TRUE
2  Jeff      M    52          FALSE
3  Carl      M    34           TRUE

Exercise

Change age values in zooDataset by adding 1 to all its values. Remember to save your transformed vector to the original age column.

Call zooDataset in a new line. When you're done, press the Run and Check Code button.

Stuck? Here's a hint!

You should write:

zooDataset$age <- zooDataset$age +1

and then call the zooDataset variable.