nsprintf provides a single function, nsprintf()
, which makes it simple to construct internationalized message pluralizations.
This is a common problem in writing pluralized R messages that are communicated to the end-user. For example, imagine that you have code that executes an operation one or more times and you wish to communicate the number of iterations to the end-user via message()
, warning()
, or error()
. You can address that in a number of ways, one of which is simply ignoring pluralization entirely:
n <- 2; message(paste0(n, " iterations occurred")) n <- 1; message(paste0(n, " iterations occurred"))
The grammatical failure is obnoxious. Another is to construct an if-else loop based on the value of n
:
n <- 2 if (n == 1) { message("One iteration occurred") } else { message(paste0(n, " iterations occurred")) }
This, however, is not internationalized code. No matter what language the end-user operates in, they will receive messages in English. The code itself is also verbose. The solution offered by base R, is ngettext()
, which internationalizes the code, allowing a package developer to write translations using gettext. In this form, the code becomes:
n <- 2 sprintf(ngettext(n, "%d iteration occurred", "%d iterations occurred"), n)
If message translations are available, this code will invoke a gettext translation catalog to report a locally appropriate message translation. Unfortunately, the code is verbose and requires remembering two different function names. nsprintf implements this as a single function:
library("nsprintf") n <- 2 nsprintf(n, "%d iteration occurred", "%d iterations occurred")
The package is available on CRAN and can be installed directly in R using:
install.packages("nsprintf")
The latest development version on GitHub can be installed using itself:
if (!require("ghit")) { install.packages("ghit") } ghit::install_github("RL10N/nsprintf")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.