rfunction

Converting R function argument into a string


I have a function that looks like

my_function <- function(object)
{
  # code goes here
}

I'd like the function (among other things) to print the name of the argument (as passed to the function). So if my function call is:

xxx <- my_function(my_object)

then I'd like to know how to get the function to print out the string "my_object".

Can anyone help please?


Solution

  • I would suggest next approach which is closer to what you want. For sure you could modify it to obtain other outputs:

    #Function
    my_function <- function(x)
    {
      as.character(eval(parse(text=enquo(x)))[2])
    }
    #Apply
    my_function(x = my_object)
    

    Output:

    [1] "my_object"
    

    An improvement thanks to @MrFlick is next:

    #Function
    my_function <- function(x)
    {
      rlang::as_label(rlang::enquo(x))
    }
    #Apply
    my_function(x = my_object)
    

    Which produces same output with a more elegant style in the function:

    [1] "my_object"