The pipe %>%
can be used to perform operations sequentially
without having to define intermediate objects. Start by redefining
murder to include rate and rank.
murders <- mutate(murders, rate = total / population * 100000,
rank = rank(-rate))
In the solution to the previous exercise, we did the following:
murders_filtered <- filter(murders, region %in% c("Northeast", "West") &
rate < 1)
my_states <- select(murders_filtered, state, rate, rank)
The pipe %>%
permits us to perform both operations sequentially
without having to define an intermediate variable. We
therefore could have mutated and selected in the same line like this:
my_states <- murders %>%
mutate(rate = total / population * 100000, rank = rank(-rate)) %>%
select(state, rate, rank)
Notice that mutate
and select
no longer have a data frame as the first argument.
The first argument is assumed to be the result of the operation
conducted right before the %>%
.
Load the original murders
table by using data(murders)
. Use
a pipe to create a new data frame called my_states
that considers only
states in the Northeast or West which have a murder rate lower than 1,
and contains only the state, rate and rank columns. The pipe should also
have four components separated by three %>%
.