Get name of dataframe passed through pipe in R

大兔子大兔子 提交于 2019-11-27 02:53:41

问题


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"

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 "."

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


回答1:


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"

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.



来源:https://stackoverflow.com/questions/42560389/get-name-of-dataframe-passed-through-pipe-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!