3

This is a little frustrating, and I'm sure there's an easy answer.

history(max.show=N) will display N lines of history on to the terminal. savehistory(file) will save a number of lines of history to a file, depending on some environment variable. What I would like to do is

savehistory(file, max.show=N) 

To do this in one line instead of having to copy or trawl through a history file for the lines I want would make things much easier.

Is there a quick function/way to save a specified number of lines to a specified file?

MattLBeck
  • 5,701
  • 7
  • 40
  • 56

1 Answers1

4

I think your best bet is to abuse the history function:

history2file <- function (fname, max.show = 25, reverse = FALSE, pattern, ...) 
{
## Special version of history() which dumps its result to 'fname'
    file1 <- tempfile("Rrawhist")
    savehistory(file1)
    rawhist <- readLines(file1)
    unlink(file1)
    if (!missing(pattern)) 
        rawhist <- unique(grep(pattern, rawhist, value = TRUE, 
            ...))
    nlines <- length(rawhist)
    if (nlines) {
        inds <- max(1, nlines - max.show):nlines
        if (reverse) 
            inds <- rev(inds)
    }
    else inds <- integer()
    writeLines(rawhist[inds], fname)
}
history2file("/tmp/bla")

I would however stimulate you to start working in script files directly, and not do stuff on the command line and then later try to piece a script together.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • Thanks. Could you give me an example of the kind of working methodology that you are talking about? – MattLBeck Mar 21 '12 at 14:37
  • What I mean is that you always work in a script file. Only to test small things I tinker around with the command line. Once I did something substantial, I'll add it to the script I'm working on. In this way you can always keep record of what you did, at least of what was important. Doing a lot in the command line forces you to think hard about what you did later on. By working in a script, you always know what you did. – Paul Hiemstra Mar 21 '12 at 15:14