How can I save the specified number of lines from R history to a file?

This is a little frustrating and I'm sure there is a simple answer.


will display N lines of history on the terminal. savehistory(file)

will save several lines of history to a file, depending on some environment variable. What I would like to do is



To do this in one line, instead of copying or trailing through the history file for the lines I want, would be much easier.

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


source to share

1 answer

I find it best to use the history function:

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


I would encourage you to start working in the script files directly, rather than doing things on the command line, and then try to merge the script together.



All Articles