How to use quotation API to implement inplace mutate helper?

19 views
Skip to first unread message

holger brandl

unread,
Dec 7, 2017, 8:38:10 AM12/7/17
to manipulatr
Hi,

I'm exploring the quotation API to write custom verbs. My idea is to streamline column transforms within a pipe. So I'd love to inline 

iris$Species %<>% str_replace("vir", "foo")

into a piped chain. I know I could do

iris %>% mutate(Species = Species %>% str_replace("vir", "foo"))

but to make it more concise I'd rather like to write just

iris %>% mutate_inplace(Species, str_replace("vir", "foo"))

which I have tried to implement as

mutate_inplace = function(df, variable, expr){
quoVar <- enquo(variable)
varName = quo_name(quoVar)

mutate(df, !!varName := quoVar %>% !!enquo(expr))
}

However this fails with the error:

Error in mutate_impl(.data, dots) : 

  Column `Species` is of unsupported type quoted call


What am I doing wrong here?

Thanks,
best,
Holger


Romain Francois

unread,
Dec 7, 2017, 9:04:48 AM12/7/17
to holger brandl, manipulatr
Hello, 

That sounds like a job for mutate_at 

iris %>% mutate_at("Species", funs(str_replace(., "vir", "foo")))


Otherwise, I have something close to your example, using enexpr instead of enquo, I could not make quosures and pipes interact nicely: 

mutate_inplace <- function(data, var, expr ){
  var      <- enexpr(var)
  var_name <- quo_name(var) 
  expr <- enexpr(expr)

  call <- quo( UQ(var) %>% UQ(expr) )
  print(call)
  mutate( data, !!var_name := UQ(call) )
}

mutate_inplace( iris, Species, str_replace("vir", "foo") )

Romain


--
You received this message because you are subscribed to the Google Groups "manipulatr" group.
To unsubscribe from this group and stop receiving emails from it, send an email to manipulatr+unsubscribe@googlegroups.com.
To post to this group, send email to manip...@googlegroups.com.
Visit this group at https://groups.google.com/group/manipulatr.
For more options, visit https://groups.google.com/d/optout.

Holger Brandl

unread,
Dec 7, 2017, 11:18:39 AM12/7/17
to Romain Francois, manipulatr
Thanks Romain, works perfectly!

To unsubscribe from this group and stop receiving emails from it, send an email to manipulatr+...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages