Skip to content

Instantly share code, notes, and snippets.

@jimhester
Created August 30, 2019 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jimhester/05d45488a9727c342196b87108a10559 to your computer and use it in GitHub Desktop.
Save jimhester/05d45488a9727c342196b87108a10559 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