Getting the right output can be trying

I recently undertook a broad study of the base package, and came across the ngettext() function, which allows one to provided alternative text output relevant to certain locales. It’s funny when you see some software that want to output a phrase like “only __ oranges eaten…”, in trying to fill in the numbers, get stuck when the value is 1. I didn’t want that to happen this time around.

In R, ngettext() makes it easy for us to appear a little intelligent, at least in the English language. In using this function, the phrase mentioned in the preceding paragraph would yield “only 1 orange eaten…”. (I don’t know how this function works for other languages yet, but hope to find out soon.)

But today, it was a bit of struggle for me (Gosh, ignorance is such a pain!) as I had created a function to update a local database of tweets, which was a wrapper around search_twitter_and_store() from Jeff Gentry’s twitteR package. My team at work has this little report that we prepare every week and having to download data every single time we render the document in Rmarkdown was becoming a laborious, especially given the touchy internet service. So I wanted to have an easy-to-use function to update the database only when and if necessary. I also wanted a nicely formatted printout to the console that would inform the user on the extent of the update. Unfortunately for me, whenever it returned 0,  I ended up with just “tweets added.“, with no number shown.

Next, I tried ngettext(n, "tweet loaded.", "tweets loaded."), where ‘n’ is the number found and stored by the function in the twitteR package. No way.

After messing around with this for quite a while, I had another look at the documentation and found my mistake – for me to get consistent results I had to rely on sprintf()‘s C-esque placeholders! To cap it up, I passed everything to cat() for a neat printout. Phew.

Moral of the story: Read the manual.

Here’s the portion of the script I was playing around with:


# ... Twitter OAuth registration ...
# ... 

updateDB <- function() {
n <- search_twitter_and_store("rstats", table_name = "rstats_tweets")
cat(sprintf(ngettext(n, "%d tweet loaded.", "%d tweets loaded."), n))

# Use the function (immediately after recent DB update)

O tweets loaded.


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s