Search code examples
rdplyrmagrittr

Magrittr two way pipe and multiple conditions?


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!


Solution

  • 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))