[R] How to get commands history as a character vector instead of displaying them?

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Mon Mar 23 11:13:07 CET 2009


Romain Francois wrote:
> Yihui Xie wrote:
>> Hi Everyone,
>>
>> I want to get the commands history as a character vector instead of
>> just displaying them, but the function history() just returns NULL. I
>> checked the source code of 'history' and could not find a solution.
>> Anybody has an idea? Thanks!
>>   
> history eventually calls file.show, which will use the pager option to
> determine how to show the file, so you can do something like that:
>
> history <- function( ... ){
> old.op <- options( pager = function( files, header, title, delete.file
> ) readLines( files ) ); on.exit( options( old.op ) )
> utils::history(...)
> }
> history( pattern = "png" )

i think the following is an acceptable alternative:

    history = function() {
       file = tempfile()
       on.exit(unlink(file))
       savehistory(file)
       readLines(file) }

the output is *lines* of text, but if you need whole executable
expressions, you can parse the output:

    1 + 1
    ph = parse(text=history())
    as.list(ph)
    ph[length(ph)-1]
    # expression(1 + 1)
    eval(ph[length(ph)-1])
    # [1] 2


vQ




More information about the R-help mailing list