Thursday, 21 April 2016

R tip: run commands without brackets

Using R, I often want to type quick commands in. But R commands always have brackets. Typing brackets (e.g. ls()) is a big hassle. I find myself missing the unix command line where you can just type ls.

So, here’s a quick hack to do just that. Put the following in your .Rprofile file in your home directory.


print.command <- function (x) {
  default.args <- attr(x, "default.args")
  if (! length(default.args)) default.args <- list()
  res <- do.call(x, default.args, envir=parent.frame(2))
  if (attr(x, "print_result")) print(res)
  invisible(NULL)
}

make_command <- function(x, ..., print = TRUE) {
  class(x) <- c("command", class(x))
  attr(x, "default.args") <- list(...)
  attr(x, "print_result") <- print
  x
}


Now, just add the following for any command that you’d like to type without brackets. For example, for ls:

ls <- make_command(ls)

From now on, typing the command will run it.

If you want to include default arguments, add them as arguments to make_command, and if you don’t want to print the result, add the argument print = false. So, for a quick way to turn debugging on, I use:

oer <- make_command(options, error = recover, print = FALSE)

Typing oer at the command line now runs options(error = recover). All without undue stress on my little finger and the Shift key.

No comments:

Post a Comment