Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

history

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?

like image 402
MattLBeck Avatar asked Oct 26 '25 02:10

MattLBeck


1 Answers

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.

like image 51
Paul Hiemstra Avatar answered Oct 28 '25 14:10

Paul Hiemstra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!