13.11 mutate() & transform ()

  • Transformations are executed line-by-line
  • dplyr contains the functions mutate(), transform(), transmute()
mutate(swiss, Examination10 = Examination*10, FertAgri = Fertility - Agriculture)
# Q: What does the above function do?

# Don't forget to assign the result to a new object if you want to save it!

# mutate() allows you to refer to variable you just created, transform() doesnt
mutate(swiss, Examination10 = Examination*10, NewExi = Examination10 - 10)
transform(swiss, Examination10 = Examination*10, NewExi = Examination10 - 10)

# Use transmute if you only wan't to keep new variables
transmute(swiss, Examination10 = Examination*10, NewExi = Examination10 - 10)

# Q: What if I want to get a new data set only with the variable Catholic but dividid by 10? What do I have to write?


13.11.1 Exercise: Filtering, reordering, selecting/renaming, extracting and transforming

  1. Execute the following code: swiss2 <- cbind(swiss, row.names(swiss)). Compare swiss and swiss2 with View() and explain what it does!
  2. Use the dataset swiss (?swiss).
    1. Extract columns 2 and 3 and save them in a new object. (Tip: Access through names() or simply the column numbers)
    2. Extract the rows 2 to 6 from columns 1 and 4 and save them in a new object.
    3. Extract observations 1, 3, and 6 from columns 2, 4, 6 and save them in a new object.
  3. Extract all provinces from the data set swiss (?swiss) that have values on the variable Agriculture that are smaller or equal than 20 and bigger or equal than 80 (Agriculture <= 20 or >= 80). Save the results in a new data frame, that comprises the first 3 variables/columns of the old data set.
  4. Reorder the observations/rows in the data set swiss according to the variable Infant.Mortality. Which province has the highest level of Infant.Mortality?
  5. Add a new variable/column called Infant.Mortality.squared that contains the squared values of the variable Infant.Mortality.


13.11.2 Solution: Filtering, reordering, selecting/renaming, extracting and transforming