Reputation: 1817
I want a column x
to be filled with the value of cyl
when mpg
is at its lowest.
In base R I could write something like
mtcars$x = mtcars[min(mtcars$mpg), "cyl"]
How would I write something like this using dplyr
?
Upvotes: 0
Views: 139
Reputation: 48
Using a combination of mutate and ifelse you will be able to achieve the desired effect!
When mpg is not at its lowest, x's value will be NA
library(dplyr)
mtcars%>%
mutate(x = ifelse(mpg == min(mpg), cyl, NA))
Upvotes: 0
Reputation: 174506
I think you just want
mtcars %>% mutate(x = cyl[which.min(mpg)])
Upvotes: 4