Is it possible to convert regular R code to its pipe version?

Viewed 80

Is there any add-in or package that allows to transform code from a regular R version to its pipe version ?

library(dplyr)
# Regular R version
data <- mtcars
data <- mutate(data, cyl2 = - cyl)
data2 <- subset(data, cyl2 < - 3) # I use a non-dplyr verb on purpose

# Piped version
data2 <- mtcars %>% 
  mutate(cyl2 = - cyl) %>% 
  subset(cyl2 < - 3)
1 Answers

There is no such package/add-on that I know of. It's fairly self-explanatory why: the software would have no way of consistently knowing what is pipeable because functions can both place their arguments in different orders and also name their arguments something else.

For example, consider data.frame(x=5) %>% foo(). It could well be that foo(., arg) produces a different result than foo(arg, .). Even if the software somehow looked at the names of the arguments and made an educated guess, such as "any argument named data contains the data", (a) that assumption may be incorrect (perhaps df needs the data or data needs the dimensionality of the data) and (b) the inconsistency would presumably be enough that it would require a lot of continuous, presumably-human checking and continuous maintenance, and (c) it's not a well-defined problem in itself: dplyr::left_join(x1, x2) can be accomplished with x1 %>% left_join(., x2), x2 %>% left_join(x1, .), etc.

Related