获取通过R中的管道传递的数据帧的名称 [英] Get name of dataframe passed through pipe in R

查看:57
本文介绍了获取通过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.

推荐答案

这是第一次尝试,虽然有点破解,但似乎可行。

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"

管道函数创建一个跟踪链部分的环境。我尝试在当前执行环境中查找该变量,然后使用存储在其中的 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中的管道传递的数据帧的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆