2

Is there a function that will recall the last line executed within an R script? For example, if such a function existed and was called "echoLast", I am interested in using this in the following manner:

y <-3,
whi <- 4,
x <- 5
wlo <- 6

sum <- y * whi + x * wlo

last.command <- echoLast()
print(paste(last.command,sum,y,whi,x,wlo))

which would result in output of:

"sum <- y * whi + x * wlo 32 2 1 5 6"

Thank you

  • 2
    `.Last.value`? https://stat.ethz.ch/R-manual/R-devel/library/base/html/Last.value.html – Jon Spring Jul 23 '19 at 03:22
  • 1
    for `last.command`, you can try `fname <- tempfile(); savehistory(fname); head(tail(readLines(fname), 3), 1)`. dont think there is a good way to capture `y`, `whi`, `x` and `wlo` when they are not in a function. check out `match.call` to capture arguments passed into a function – chinsoon12 Jul 23 '19 at 03:49
  • 1
    I would argue that what this user is asking for is distinct from `.Last.value`, and more like the command given by @chinsoon12 ... Last output is not the same as the last call. – Brian Jul 23 '19 at 04:33
  • Correct Brian, I am not asking about last.value, I am asking for the command that generated the last value. As far as I am aware, this is not a duplicate question. – Greg Landry Jul 23 '19 at 15:44
  • Thanks @chinsoon12. This works nicely. – Greg Landry Jul 23 '19 at 16:15

1 Answers1

0

You can try something like:

f <- function() {
    lv <- .Last.value

    fname <- tempfile()
    savehistory(fname)
    lastcmd <- head(tail(readLines(fname), 2), 1)

    parts <- strsplit(gsub("[^[:alnum:] ]", "", lastcmd), " +")[[1]]
    vars <- as.list.environment(.GlobalEnv)
    c(list(Last.command=lastcmd, Last.value=lv), vars[names(vars) %in% parts])
}

y <- 3
whi <- 4
x <- 5
wlo <- 6

sum <- y * whi + x * wlo
f()

output:

$`Last.command`
[1] "sum <- y * whi + x * wlo"

$Last.value
[1] 42

$x
[1] 5

$y
[1] 3

$sum
[1] 42

$whi
[1] 4

$wlo
[1] 6

Caveat: does not when it is run from source

chinsoon12
  • 25,005
  • 4
  • 25
  • 35