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.
Related videos on Youtube
Author by
luciano
Updated on September 24, 2022Comments
-
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 almost 11 yearsif you call
removeRows
as it stands now, R will create a copy of yourdataframe
and modify the copy. When the function terminates, the (modified) copy is destroyed, and the originaldataframe
will be untouched. If you want to change the original data, you must call it asmtcars <- removeRows(mtcars, 5)
AND add the linedataframe
(orreturn(dataframe)
) at the end of the function code.
-
-
krlmlr almost 11 yearsAre you aware of a similar idiom in Python? (OT, but I'm just wondering...)
-
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 almost 11 yearsThanks. It's just that I'd be so glad to be able to write just
loginfo(expression)
instead ofloginfo("expression: %s" % expression)
... -- Just found it: In Python, there is another option to achieve this: github.com/lihaoyi/macropy#tracing