John-Henry
John-Henry

Reputation: 1817

How do you fill a column with a value conditional on another column?

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

Answers (2)

cbaylor
cbaylor

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

Allan Cameron
Allan Cameron

Reputation: 174506

I think you just want

mtcars %>% mutate(x = cyl[which.min(mpg)])

Upvotes: 4

Related Questions