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

假装没事ソ 提交于 2019-12-10 18:13:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9806333/how-can-i-save-a-specified-number-of-lines-from-rs-history-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!