[SOLVED] Print dataframe name in function output

Issue

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?

Solution

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.

Answered By – Konrad Rudolph

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *