本文介绍了获取通过管道在 R 中传递的数据帧的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够打印通过管道传递的数据帧的名称.这可能吗?我可以.

I would like to be able to print the name of a dataframe passed through the pipe. Is this possible? I can do.

printname <- function(df){
    print(paste(substitute(df)))
}
printname(mtcars)
#[1] "mtcars"

但是,它返回."当这个函数使用 magrittr 管道传输时.

However, it returns "." when this function is piped using the magrittr pipe.

mtcars %>% printname
# [1] "."

这在编写用于记录的生产过程的函数的自定义错误消息时会很有帮助——如果日志中唯一的内容是.",则很难知道哪里出错了.

This would be helpful when writing custom error messages of functions used in logged production processes -- it's hard to know where something failed if the only thing in the log is "."

返回原始调用可能就足够了,其中包括 mtcars %>% 部分.

It would probably be enough to return the original call, which would include the mtcars %>% piece.

推荐答案

这是第一次尝试,有点像 hack,但似乎可行.

This is a first attempt, it's kind of a hack, but seems like it might work.

find_chain_parts <- function() {
    i <- 1
    while(!("chain_parts" %in% ls(envir=parent.frame(i))) && i < sys.nframe()) {
          i <- i+1
      }
    parent.frame(i)
}

printfirstname <- function(df){
    ee <- find_chain_parts()
    print(deparse(ee$lhs))
}

mtcars %>% printfirstname
# [1] "mtcars"

pipe 函数创建了一个跟踪链部件的环境.我尝试在当前执行环境中查找此变量,然后使用存储在那里的 lhs 信息来查找管道开头的符号.这没有经过很好的测试.

The pipe function creates an environment that keeps track of the chain parts. I tried walking up the current execution environments looking for this variable and then use the lhs info stored there to find the symbol at the start of the pipe. This isn't well tested.

这篇关于获取通过管道在 R 中传递的数据帧的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:55