Search code examples
rellipsis

Identifying string and column names passed as arguments via ellipses in R


I have been using ellipses in R to pass arguments to a function the arguments are typically in the format (col1,filter1,col2,filter2...) passed via function call as

df <- function_x(treaty_id,"abc",country,"usa")

please note that the column names are not passed under double quotes only the filters are.

 function_x <- function(...){
      
      colnam1 <- enquo(..1)
      filter1 <-  (..2)
      colnam2 <- enquo(..3)
      filter2 <-  (..4)
      
if(filter1 == "usa")
{

 if(quo_name(colname1) == "treaty_id")
    { then do something}
}
      

The problem is i dont think the first if condition on filter1 is not working in R. Also can you please suggest if treatment of second if condition is correct.

I have been really struggling with it so thanks in advance.


Solution

  • The treatment of your if statements is technically correct. You can use rlang::enquo to capture the quosure and then use rlang::quo_name to return the object name or expression as string. You can use this string in the if clause to trigger different actions.

    library(rlang)
    
    function_x <- function(...){
      
      colnam1 <- enquo(..1)
      filter1 <- (..2)
      colnam2 <- enquo(..3)
      filter2 <- (..4)
      
      if (filter1 == "abc") {
        print("do one thing here")
      if (quo_name(colnam1) == "treaty_id") {
        print("and do something here")
        }
      }
    }
    
    function_x(treaty_id,"abc",country,"usa")
    #> [1] "do one thing here"
    #> [1] "and do something here"
    

    Created on 2023-09-22 with reprex v2.0.2