0

I am relatively new to R and dplyr library. How can I get the function to use the name of the mutated columns as the argument pass in the function?

For example, I want "test" as the name of the mutated column but I get "y". What am I doing wrong? Thank you

 library(dplyr)
    d <- data.frame(alpha=1:3, beta=4:6)
    d
    compare_status<-function(x,y){
      x %>% mutate(y=ifelse(alpha ==2,"G2","0"))
    }

    compare_status(d,test)
4
  • 1
    We were just discussing this yesterday. R is strict about not evaluating the name of the object. There is a new dplyr coming out soon that claims to be able to solve this. If you would like, download the devel version to test it all out. And read through this tutorial dplyr.tidyverse.org/articles/programming.html Commented Apr 20, 2017 at 16:53
  • Thanks for the pointer. Is it only for functions that "mutate"? Commented Apr 20, 2017 at 16:55
  • 1
    No it is strict across all parts of naming positions as far as I have seen. Commented Apr 20, 2017 at 16:58
  • Presumably the restriction is there so that a user can write c(x=1) rather than c("x"=1). At this point, even if the R gods saw fit to evaluate the left-hand side, they couldn't because so much code written in the past is depending on the value entered being the value shown. Too late to change. Commented Apr 20, 2017 at 17:14

1 Answer 1

2

We can use the devel version dplyr syntax for this (soon to be released 0.6.0)

compare_status<-function(x,y){
   y <- quo_name(enquo(y))
    x %>%
      mutate(!!y := ifelse(alpha ==2,"G2","0"))
}

compare_status(d,test)
#  alpha beta test
#1     1    4    0
#2     2    5   G2
#3     3    6    0

The enquo take the input arguments and convert to quosure, which is then converted to strings with quo_name and unquoted with !! or UQ for evaluation as column name on the lhs of assign (:=)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.