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.
pmin
i.e.transform(df, v3=ifelse(v1!=0, v1/do.call(pmin, df), 0))
– Chromousplyr
package here? I don't remember which should be loaded first, but in this case you shouldn't loadplyr
at all. – Schrockdo
, or best would bepmin
– Chromousmin
andpmin
, or rather why the first does not work in a data frame like mine? – Sungkiangdf %>% mutate(v3 = (v1 != 0) * v1/pmin(v1,v2))
? – Vaclavdo
, ie.df %>% rowwise() %>% do(data.frame(., v3=(.$v1!=0)*.$v1/min(.$v1, .$v2)))
– Chromousmutate
withrowwise
-df %>% rowwise %>% mutate(v3 = ifelse(v1 != 0, v1/min(v1, v2), 0))
– Clue