R – How to concatenate String and an output evaluated from a function in R

rstatistics

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.

Best Answer

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.