Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: use min() within dplyr::mutate()

Tags:

r

dplyr

min

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 v3as 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.

like image 772
user3375672 Avatar asked Jan 21 '15 15:01

user3375672


People also ask

What does mutate in dplyr do?

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.

How do I use the mutate function in R?

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.

How do I mutate a value in R?

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.


1 Answers

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).

like image 91
talat Avatar answered Nov 10 '22 06:11

talat