7.1 mutate & transmute
mutate
allows to create new columns that are functions of the existing ones.
- Create a new column with the duration of each term:
# Subtracting column start to column end
mutate(presidential,
duration_days=end-start)
Notes:
- Use unquoted column names.
- Columns are added at the end of the data frame.
mutate
keeps all columns.
You can change where the column is added (if you don’t want it to be added at the last position):
# add it before column "start"
mutate(presidential,
duration_days=end-start,
.before=start)
# add it after column "end"
mutate(presidential,
duration_days=end-start,
.after=end)
If you want to keep only the newly created column(s) (drop the remaining ones): use transmute()
instead of mutate()
:
transmute(presidential,
duration_days=end - start)
Re-assign to a new - or the same - data frame/tibble using the usual R assignment operator: <-
<- mutate(presidential,
presidential2 duration_days=end - start)
- If you want to change the name of a column, you can use the function
rename
:
# using the column name:
rename(presidential2,
President=name)
# or the column index:
rename(presidential2,
President=1)
# you can rename several columns using the same command:
rename(presidential2,
President=name,
Political_party=party)