I have a dataframe with a list of names I want to keep, the rest I want to recode to "Other".
namesToKeep = data.frame(
car = c("Merc 240D", "Cadillac Fleetwood"),
reason = c("Great car","Me like")
)
selectedCars <- namesToKeep$car
names(selectedCars) <- selectedCars
mtcars %>% mutate(CarName = rownames(mtcars)) %>%
mutate(
CarName = recode(CarName, !!!selectedCars, .default = "Other")
)
The above code works, and demonstrates what I want to do. But I would like to clean it up a bit and not have to calculate a named vector of selected names before hand.
Using base R I can do this by directly mutating the dataframe but I wonder what is the idiomatic dplry way of doing this?