Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print dataframe name in function output

Tags:

function

r

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?

like image 983
luciano Avatar asked May 24 '13 20:05

luciano


1 Answers

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.

like image 112
Konrad Rudolph Avatar answered Nov 07 '22 11:11

Konrad Rudolph