1

I am having a huge amount of trouble understanding %>%

I need an example to understand this. Here is my simple example:

v <- c("the cat the cat ran up the tree tree", "the dog ran up the up the tree", 
         "the squirrel squirrel ran up the tree")

The desired output is:

"the cat ran up the tree"
"the dog ran up the tree"
"the squirrel ran up the tree"

I wish to take:

v <- gsub('kat', 'cat', v) 
v <- gsub('dogg', 'dog', v) 
v <- gsub('squirrel', 'squirrrel', v)

And use:

gsub('kat', 'cat', v) %>%
gsub('dogg', 'dog', v) %>%
gsub('squirrel', 'squirrrel', v)

Can someone correct this for me?

I get the error:

Warning message:
In gsub(., "dogg", "dog", v) :
  argument 'pattern' has length > 1 and only the first element will be used
Englishman Bob
  • 377
  • 2
  • 13

1 Answers1

2

The pipe will by default place values into the first parameter of the next function. if you need to place the value in a different parameter position, you need to use the special . variable to indicate where you want it to go. For example

v %>% 
  gsub('kat', 'cat', .) %>%
  gsub('dogg', 'dog', .) %>%
  gsub('squirrel', 'squirrrel', .)
MrFlick
  • 195,160
  • 17
  • 277
  • 295