【问题标题】:Print dataframe name in function output在函数输出中打印数据帧名称
【发布时间】:2013-05-24 20:14:27
【问题描述】:

我有一个看起来像这样的函数:

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

我可以使用这样的函数从数据框中删除第 5 行:

removeRows(mtcars, 5)

函数输出此消息:

"The 5th row was removed from xxxxxxx"

如何将 xxxxxxx 替换为我使用过的数据框的名称,所以在这种情况下为mtcars

【问题讨论】:

  • 您知道dataframe &lt;- dataframe[rows.remove,] 会在函数调用之外传播更改吗?另外,rows.remove 应该是否定的
  • 帖子已编辑至-rows.remove。抱歉,不明白您所说的“不在函数调用之外传播更改”是什么意思。这是我的错,不是你的。可以扩展一下吗?
  • 如果您现在调用removeRows,R 将创建您的dataframe 的副本并修改该副本。当函数终止时,(修改后的)副本被销毁,原始的dataframe 将保持不变。如果要更改原始数据,必须将其调用为mtcars &lt;- removeRows(mtcars, 5),并在函数代码末尾添加dataframe(或return(dataframe))行。

标签: r function


【解决方案1】:

您需要在未评估的上下文中访问变量名称。我们可以为此使用substitute

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))
}

其实这就是它的主要用途;根据文档,

substitute 的典型用途是为数据集和绘图创建信息标签。

【讨论】:

  • 你知道 Python 中有类似的成语吗? (OT,但我只是想知道......)
  • @krlmlr Python 没有这样的东西——substitute 本质上是一个 hack。但是,您可以在 Python 中检查调用堆栈——它可能能够通过它检索参数名称,但它会更加复杂,因为您必须检索和检查调用上下文的字节码。
  • 谢谢。只是我很高兴能够只写 loginfo(expression) 而不是 loginfo("expression: %s" % expression)... -- 刚刚发现:在 Python 中,还有另一种选择:github.com/lihaoyi/macropy#tracing
猜你喜欢
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 2016-03-15
相关资源
最近更新 更多