Skip to content

Instantly share code, notes, and snippets.

@EvaMaeRey
Forked from jimhester/previous_commands.R
Created September 1, 2019 01:44
Show Gist options
  • Select an option

  • Save EvaMaeRey/25447b91d99cbeb59ffbd465c63c3965 to your computer and use it in GitHub Desktop.

Select an option

Save EvaMaeRey/25447b91d99cbeb59ffbd465c63c3965 to your computer and use it in GitHub Desktop.
Get the previous commands as a text string in RStudio
# RStudio overrides `history()`, `loadhistory()` and `savehistory()`,
# so they work somewhat differently than on the console version of R.
# This saves the current history to a temporary file then reads the last
# line of it (or more depending on the `n` argument)
#
# It does not handle multi-line commands, which would be more tricky to handle...
previous_commands <- function(n = 1) {
tf <- tempfile()
on.exit(unlink(tf))
savehistory(tf)
head(tail(readLines(tf), n = n + 1), n = n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment