mutate_cond | R Documentation |
The mutate_cond()
function allows simple conditional mutations
of data.frames
by combining a conditional to select rows, followed by
dplyr::mutate()
syntax to specify how to change columns. This function is
inspired by, and based on, a function proposed in a discussion on Stack Overflow.
This function, however, extends the original mutate_cond()
function
proposed in that thread by falling back on using base::transform()
if the
dplyr
package is not installed.
mutate_cond(
.data,
.condition,
...,
.envir = parent.frame(),
.method = c("default", "dplyr", "base")
)
.data |
The data.frame to mutate. |
.condition |
Conditional statement determining which rows to modify. |
... |
One or more statements determining which columns to mutate and how. |
.envir |
Which environment to use for evaluation. |
.method |
Which underlying method to use for the mutation. Acceptable values are:
|
All named parameters are prefixed with .
to reduce the probability of
conflict with the column names that are to be mutated, which are specified in
the ...
parameter.
The function relies on either dplyr::mutate()
if available, or
base::transform()
if the dplyr
package is available. Specifying multiple
mutations in ...
is allowed, but, if doing so, it is important to be aware
of the differences between mutate()
and transform()
. The two
functions are very similar, apart from the fact that mutate()
executes the
transformations in an iterative manner, so that later transformations can use
the columns created by earlier transformations, whereas transform()
uses
the values from the original data.frame
, regardless of the number of steps.
# Set dist to 3 where speed is 7 or less
result <- mutate_cond(cars, speed<=7, dist=3)
head(result)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.