R.Last.call功能 - 类似于.Last.value

时间:2015-05-31 01:09:14

标签: r

.Last.value类似,有没有办法访问最后一次通话?低于潜在.Last.call的预期结果。

sum(1, 2)
# [1] 3
str(.Last.call)
#  language sum(1, 2)

如果不需要从文件系统解析文件,则为bests。

2 个答案:

答案 0 :(得分:3)

last.call包已经不在了,但你仍然可以获得代码:

# -----------------------------------------------------------------------
# FUNCTION: last.call
#   Retrieves a CALL from the history and returns an unevaluated 
#   call.
#
#   There are two uses for such abilities.  
#   - To be able to recall the previous commands, like pressing the up key
#     on the terminal.
#   - The ability to get the line that called the function.
#   
#   TODO:
#   - does not handle commands seperated by ';'
#
# -----------------------------------------------------------------------

last.call <-
function(n=1) {

 f1 <- tempfile()
 try( savehistory(f1), silent=TRUE ) 
 try( rawhist <- readLines(f1), silent=TRUE )
 unlink(f1)

 if( exists('rawhist') ) { 

   # LOOK BACK max(n)+ LINES UNTIL YOU HAVE n COMMANDS 
   cmds <- expression() 
   n.lines <- max(abs(n)) 
   while( length(cmds) < max(abs(n)) ) { 
      lines <- tail( rawhist, n=n.lines )
      try( cmds <- parse( text=lines ), silent=TRUE ) 
      n.lines <- n.lines + 1 
      if( n.lines > length(rawhist) ) break 
   }
   ret <- rev(cmds)[n] 
   if( length(ret) == 1 ) return(ret[[1]]) else return(ret) 

 }

 return(NULL)

}

现在,使用它:

sum(1, 2)
# [1] 3
last.call(2)
# sum(1, 2)

答案 1 :(得分:0)

我已经修改了这段代码,以保留原始调用中各行的格式,从而输出上述命令/调用的文本字符串,以便我可以使用cat()输出调用(用于在前一个功能运行完毕后向我发送电子邮件的功能)。这是代码:

lastCall <- function(num.call = 1) {
    history.file <- tempfile()
    try(savehistory(history.file), silent = TRUE ) 
    try(raw.history <- readLines(history.file), silent = TRUE )
    unlink(history.file)
    if (exists('raw.history') ) { 
        # LOOK BACK max(n)+ LINES UNTIL YOU HAVE n COMMANDS 
        commands <- expression() 
        num.line <- max(abs(num.call) + 1) 
        while (length(commands) < max(abs(num.call) + 1)) { 
            lines <- tail(raw.history, n = num.line)
            try(commands <- parse(text = lines), silent = TRUE) 
            num.line <- num.line + 1 
            if (num.line > length(raw.history)) break 
        }
        ret <- rev(commands)[num.call + 1]
        if (length(ret) == 1) {
            a <- ret[1]
        } else {
            a <- ret
        }
        # a <- rev(commands)[num.call + 1]
        out <- lapply(a, deparse) %>% 
            sapply(paste, sep = "\n", collapse = "\n")
    }
    out
}

享受!