require(plyr)
require(dplyr)
set.seed(8)
df <-
data.frame(
v1 = runif(10, -1,1),
v2 = runif(10, -1,1))
The problem:
How can I get the correct values into the min()
function as part of mutate()
- basically, I would like to assign v3
as v1
divided with the smallest of v1
and v2
.
This doesnt work:
df <-
df %>% mutate(v3=ifelse(v1 !=0, v1/min(v1,v2), 0))
I guess I am missing something really simple.
mutate() is a dplyr function that adds new variables and preserves existing ones. That's what the documentation says. So when you want to add new variables or change one already in the dataset, that's your good ally.
In R programming, the mutate function is used to create a new variable from a data set. In order to use the function, we need to install the dplyr package, which is an add-on to R that includes a host of cool functions for selecting, filtering, grouping, and arranging data.
To use mutate in R, all you need to do is call the function, specify the dataframe, and specify the name-value pair for the new variable you want to create.
From the help page on ?min
:
pmax and pmin take one or more vectors (or matrices) as arguments and return a single vector giving the ‘parallel’ maxima (or minima) of the vectors.
On the other hand:
max and min return the maximum or minimum of all the values present in their arguments
So you want to use pmin
here. With dplyr, one option - as commented above - is like this:
df %>% mutate(v3 = (v1 != 0) * v1/pmin(v1,v2))
Nice side effect here is that you can avoid using ifelse
and just mulitply with the logical vector (TRUE / FALSE which is then converted to 1 / 0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With