2015-05-31 49 views
5

.Last.value类似,是否有任何方式可以访问上次调用?低于潜在的预期结果.Last.callR .Last.call功能 - 类似于.Last.value

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

的最好成绩,如果它不会需要从文件系统解析文件。

+3

[字面第一次打在谷歌时,我输入“r last call”](http://www.inside-r.org/packages/cran/last.call/docs/last.call) – shadowtalker

+0

因此,将其作为答案 –

+0

@MikeWise我认为他们的观点是OP应该努力寻找答案,而不是第一站。 –

回答

3

last.call包不再是CRAN,但你仍然可以得到代码:

# ----------------------------------------------------------------------- 
# 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

我也在玩它现在 :)。如果您“编写”代码,则不起作用,所有东西都算作一行。 –