Data Tip: Assignment with the ’T’ Pipe

dplyr
magrittr
Author

Tinashe M. Tapera

Published

January 17, 2019

So today, I found myself in an interesting situation wherein I was writing out an R object to disk, but needed to keep the file’s name and path in session so I could do something with it later. Typically, doing that would look like this:

# first, make some data, to write to disk
mydat <- data(iris) 
fname <- "iris.csv"
write.csv(x = mydat, fname)

# do some coding
# do some coding
# do some coding

# later on, reference the file using the fname variable
file.exists(fname)
[1] TRUE
file.remove(fname)
[1] TRUE

For some, this might be perfectly fine, but I found another interesting way of doing this using magrittr’s “Tee” pipe (%T>%):

shhh <- suppressPackageStartupMessages
shhh(library(dplyr, quietly = TRUE))
shhh(library(magrittr, quietly = TRUE))

fname2 <- "iris2.csv" %T>%
  write.csv(mydat, .)

file.exists(fname2)
[1] TRUE
file.remove(fname2)
[1] TRUE

Just an interesting way to assign an object and send the LHS of the pipe along the chain in one go.