I'm wondering if there's a dplyr equivalent to
df <- data.frame(A=1:5,B=2:6,C=-1:3)
df[df==2] <- 10
I'm looking for
df %>% <??>
That is, a statement that is chainable with other dplyr verbs
1) replace Try this. It only requires magrittr although dplyr imports the relevant part of magrittr so it will work with dplyr too:
df %>% replace(. == 2, 10)
giving:
A B C
1 1 10 -1
2 10 3 0
3 3 4 1
4 4 5 10
5 5 6 3
1a) overwriting Note that the above is non-destructive so if you want to update df then you will need to assign it back:
df <- df %>% replace(. == 2, 10)
or
df %>% replace(. == 2, 10) -> df
or use the magrittr %<>% operator which eliminates referencing df twice:
df %<>% replace(. == 2, 10)
2) arithmetic This would also work:
df %>% { 10 * (. == 2) + . * (. != 2) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With