R: use min() within dplyr::mutate()
Asked Answered
S

1

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

Sungkiang answered 21/1, 2015 at 15:29 Comment(9)
You could use pmin i.e. transform(df, v3=ifelse(v1!=0, v1/do.call(pmin, df), 0))Chromous
Any particular reason you loading plyr package here? I don't remember which should be loaded first, but in this case you shouldn't load plyr at all.Schrock
Right, normally plyr first, but here only dplyr could be loaded.Sungkiang
Here I think it looking for min value of columns rather than rows. You may have to wrap with with do, or best would be pminChromous
@akrun, perfect! Can you explain briefly the difference between min and pmin, or rather why the first does not work in a data frame like mine?Sungkiang
How about df %>% mutate(v3 = (v1 != 0) * v1/pmin(v1,v2))?Vaclav
Here is a way using do, ie. df %>% rowwise() %>% do(data.frame(., v3=(.$v1!=0)*.$v1/min(.$v1, .$v2)))Chromous
Guys, how about posting some answers?Schrock
You can use mutate with rowwise - df %>% rowwise %>% mutate(v3 = ifelse(v1 != 0, v1/min(v1, v2), 0))Clue
V
35

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

Vaclav answered 21/1, 2015 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.