Print dataframe name in function output

11,952

You need to access the variable name in an unevaluated context. We can use substitute for this:

removeRows <- function(dataframe, rows.remove) {
  df.name <- deparse(substitute(dataframe))
  dataframe <- dataframe[rows.remove,]
  print(paste("The", paste0(rows.remove, "th"), "row was removed from", df.name))
}

In fact, that is its main use; as per the documentation,

The typical use of substitute is to create informative labels for data sets and plots.

Share:
11,952

Related videos on Youtube

luciano
Author by

luciano

Updated on September 24, 2022

Comments

  • luciano
    luciano over 1 year

    I have a function that looks like this:

    removeRows <- function(dataframe, rows.remove){
      dataframe <- dataframe[-rows.remove,]
      print(paste("The", paste0(rows.remove, "th"), "row was removed from", "xxxxxxx"))
    }
    

    I can use the function like this to remove the 5th row from the dataframe:

    removeRows(mtcars, 5)
    

    The function output this message:

    "The 5th row was removed from xxxxxxx"
    

    How can I replace xxxxxxx with the name of the dataframe I have used, so in this case mtcars?

    • Ferdinand.kraft
      Ferdinand.kraft almost 11 years
      if you call removeRows as it stands now, R will create a copy of your dataframe and modify the copy. When the function terminates, the (modified) copy is destroyed, and the original dataframe will be untouched. If you want to change the original data, you must call it as mtcars <- removeRows(mtcars, 5) AND add the line dataframe (or return(dataframe)) at the end of the function code.
  • krlmlr
    krlmlr almost 11 years
    Are you aware of a similar idiom in Python? (OT, but I'm just wondering...)
  • Konrad Rudolph
    Konrad Rudolph almost 11 years
    @krlmlr Python has nothing like this – substitute is essentially a hack. You can however inspect the call stack in Python – it might be able to retrieve the parameter name through that but it’s going to be more complex since you’ll have to retrieve and inspect the calling context’s byte code.
  • krlmlr
    krlmlr almost 11 years
    Thanks. It's just that I'd be so glad to be able to write just loginfo(expression) instead of loginfo("expression: %s" % expression)... -- Just found it: In Python, there is another option to achieve this: github.com/lihaoyi/macropy#tracing