Magrittr two way pipe and multiple conditions?

2.1k Views Asked by At

I'm recycling an answer from someone else's question but could someone tell me if the approach below can be used to meet multiple conditions before making the change?

library(dplyr)
library(magrittr)

df[df$tag=="ggyg",] %<>% mutate(tag="xxx")

I tried this but it isn't working.

 df[df$tag=="ggyg",] %<>%  df[df$h.tank==2,] %<>% mutate(tag="xxx")

I'm trying to use the approach above as it would save a lot of time instead of using ifelse statements to meet conditions.

Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

Instead of loading up conditions into different clauses, why not combine your conditions into one statement?

df[df$tag=="ggyg" & df$h.tank==2,] %<>% mutate(tag="xxx")

Or a little more idiomatically:

df %<>% mutate(tag = ifelse(tag == "ggyg" & h.tank == 2, "xxx", tag))
0
On

Here are 2 pure magrittr/dplyr solutions:

df %<>% inset(tag == "ggyg" & h.tank == 2,"tag","xxx")              # pure magrittr
df %<>% mutate(tag = inset(tag,tag == "ggyg" & h.tank == 2, "xxx"))  # magrittr & dplyr

And some reproducible examples:

cars2 <- head(cars)
#   speed dist
# 1     4    2
# 2     4   10
# 3     7    4
# 4     7   22
# 5     8   16
# 6     9   10

cars2 %<>% inset(.$dist==4,"speed",value=1000)
cars2 %<>% mutate(speed = inset(speed,dist==22,2000))

#   speed dist
# 1     4    2
# 2     4   10
# 3  1000    4
# 4  2000   22
# 5     8   16
# 6     9   10