Learn to Write Command Line Utilities in R - part 3

Check out the first post in this series for an index of all the other posts.

Yesterday we modified our simple sorting hat command line utility to accept it’s first argument, a name.

Those of you who’ve been playing along may have noticed that our implementation wasn’t ideal. It’s fine if you run the script with an argument, like ./sortinghat.R Daphne, but what happens if you omit the argument?

$ ./sortinghat.R
Hello NA, you can join Gryffindor

That’s not particularly great. Given that it’s not really possible to have a sensible default name we probably need to add some sort of input validation to make sure an argument has been provided.

This snippet is one approach to our argument validation problem:

if (length(args) < 1){
  stop("I think you forgot your name\n")
}

It checks whether args has less than one element and if it does, calls stop() with a message that tells us what’s wrong. Always remember to include good error messages that tell the user of your command line application exactly what went wrong. Just because you’re working on a command line utility, doesn’t mean you shouldn’t take as much care as with any other class of application. Command line tools that people love using are well designed and thought through from the user interaction perspective, just as much as any web app or desktop app.

By this point, sortinghat.R should look something like this:

#!/usr/bin/env Rscript --vanilla
args <- commandArgs(trailingOnly = TRUE)
if (length(args) < 1){
  stop("I think you forgot your name\n")
}
houses <- c("Hufflepuff", "Gryffindor", "Ravenclaw", "Slytherin")
house <- sample(houses, 1)
cat(paste0("Hello ", args[1], ", you can join ", house, "\n"))

Now, when you run it without specifying a name it should look something like this:

$ ./sortinghat.R
Error: I think you forgot your name
Execution halted

Running our command line utility

MacOS/Linux/git-bash

$ ./sortinghat.R Ramkumar
Hello Ramkumar, you can join Ravenclaw
$ ./sortinghat.R
Error: I think you forgot your name
Execution halted

Remember to type everything after the ‘$’ symbol and feel free to replace ‘Ramkumar’ with a name of your choosing. You should see output similar to that displayed above.

Windows

Don’t forget, if you’re using git-bash (see the first article for more info), you need to follow the instructions for Linux/MacOS.

sortinghat Ramkumar
Hello Ramkumar, you can join Hufflepuff
sortinghat
Error: I think you forgot your name
Execution halted

Feel free to replace ‘Ramkumar’ with a name of your choosing. You should see output similar to that displayed above.

Wrapping up

Now that we’re properly checking for input and we have an suitable error message in place for those situations where the argument is missing, we can shift our focus to the next step. In the next article we’ll finally move on from the random assignment of houses to something a little more Sorting-Hat-like.