Basically, I have the following say:
counter <- 3
k <- 9999
I would like to get R to print the following:
on the 3rd count: 9999
Does anyone what command should I use to do this? Please spell it out for me ,as I am completely new to R.
Use sprintf
> sprintf("on the %drd count: %d", counter, k)
[1] "on the 3rd count: 9999"
The basic construction is
paste("on the ", counter, "rd count: ", k, sep="")
You'll have to be a little clever to choose the right suffix for the digit (i.e. "rd" after 3, "th" after 4-9, etc. Here's a function to do it:
suffixSelector <- function(x) {
if (x%%10==1) {
suffixSelector <- "st"
} else if(x%%10==2) {
suffixSelector <- "nd"
} else if(x%%10==3) {
suffixSelector <- "rd"
} else {
suffixSelector <- "th"
}
}
Thus:
suffix <- suffixSelector(counter)
paste("on the ", counter, suffix, " count: ", k, sep="")
You need to set the sep
argument because by default paste
inserts a blank space in between strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With