qed
qed

Reputation: 23114

How to make R ignore duplicate entries in history?

R seems to remember all commands in history, including duplicates, which is really annoying. How can this behavior be changed?

For example, if I run these commands

    y = 3
    x = rnorm(15)
    x = rnorm(15)

I'll have to press up key three times to get to the first command.

Upvotes: 1

Views: 278

Answers (2)

eddi
eddi

Reputation: 49448

If you're filtering duplicates out regardless of order, the simplest thing to do is to add pattern argument to history(), e.g. history(pattern=""). Because of the peculiarities of history implementation, even having pattern="" will have the effect of filtering out the duplicates:

> history
...
    if (!missing(pattern)) 
        rawhist <- unique(grep(pattern, rawhist, value = TRUE, 
            ...))
...

And if you do care about the order, then just modify the stock history function, e.g.:

history_new = function(max.show = 25, reverse = FALSE, filter = FALSE, pattern, ...)
{
    file1 <- tempfile("Rrawhist")
    savehistory(file1)
    rawhist <- readLines(file1)
    unlink(file1)

    # the modification to stock
    if (filter)
      rawhist <- rawhist[cumsum(rle(rawhist)$lengths)]
    # end of modification

    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()
    file2 <- tempfile("hist")
    writeLines(rawhist[inds], file2)
    file.show(file2, title = "R History", delete.file = TRUE)
}

Upvotes: 3

Matthew Plourde
Matthew Plourde

Reputation: 44614

Assuming a duplicate command is a call identical to a previous one, regardless of order, you could simply do something like this:

tmp <- tempfile()
savehistory(tmp)
hist <- readLines(tmp)
hist[! duplicated(hist)]

or this, to preserve the last instance of a command

hist[! duplicated(hist, fromLast=TRUE)]

Upvotes: 2

Related Questions