Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr equivalent to DF[DF==X] <- Y

Tags:

r

dplyr

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

like image 273
CPak Avatar asked Dec 12 '25 05:12

CPak


1 Answers

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) }
like image 132
G. Grothendieck Avatar answered Dec 15 '25 23:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!