Search code examples
rdplyr

Mutate a vector within a pipe chain


I'd like to subtract 1 from a vector within a pipe chain. Example, mtcars$mpg.

x <- mtcars
# I don't want to do this:
x %>% mutate(mpg = mpg - 1)

I'm looking for something like this:

x$mpg %>% mutate(. := .-1)

If what I wrote there isn't clear in the second block, I'm trying to write, "take mpg vector then mutate it to be mpg - 1"

Is this possible?


Solution

  • mutate/summarise and other tidyverse functions expects a data.frame as .data. As we are extracting the column values, either use the magrittr helper function subtract

    library(magrittr)
    x$mpg %>%
         subtract(1)
    

    Or block the code in a {} and then update the column

    x$mpg %>%
          {. -1} -> x$mpg
    

    Or use the compound assignment operator (%<>%) for updating the column

    head(x$mpg)
    #[1] 21.0 21.0 22.8 21.4 18.7 18.1
    
    x$mpg %<>%
              {.- 1}
    head(x$mpg)
    #[1] 20.0 20.0 21.8 20.4 17.7 17.1