How do one replace the values of a subset in R with Tidyverse
?
Using the cars
data as an example, if I would like to change all the speed
lower than 30 into 0, I can use the command below:
cars[cars["speed"] < 30,] <- 0
With Tidyverse
, one can generate the same subset with more readable commands:
cars %>% filter(speed < 30) %>% mutate(speed =0)
However, this is changing the subset of data we have taken out from cars
, not the values of observations within cars
.
I might have missed something obvious but is there an intuitive way to do the same thing with Tidyverse
as well? While cars[cars["speed"] < 30,] <- 0
works fine in most cases, it becomes really unwieldy when one has more than 5 conditions to meet.