'A better way to write dplyr pipes? (without using dollar sign) [closed]

Quite often when using the tidyverse to manipulate data, I come up with a situation like the one below. Can someone explain why option 3 works, but 1 and 2 doesn't? Is there a better way than option 3 -- i.e "clean" looking code that doesn't use the dollar sign? I thought one idea with dplyr was to get away from using the dollar sign?

library(tidyverse)

# 1. Want this to work (doesn't)
mtcars %>%
  str_replace(mpg, ",", ".")

# 2. Second best (doesn't work)
mtcars %>%
  select(mpg) %>% 
  str_replace(",", ".")

# 3. This works, but don't like the use of $
mtcars$mpg %>% 
  str_replace(",", ".")

# 4. It looks even uglier when saving as an object:

mtcars$mpg <- mtcars$mpg %>% 
  str_replace(",", ".")


Solution 1:[1]

If you really want to use pipe, you can use %$% which is a part of magrittr

library(magrittr)

mtcars %$% 
  str_replace(mpg, ",", ".")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom Hoel