How to combine String and the result obtained from a function in R?

Basically, I say the following:

counter <- 3 k <- 9999 

I would like to get R to print the following:

 on the 3rd count: 9999 

Anyone which command should I use for this? Please state this for me as I am completely new to R.

+7
source share
3 answers

Basic construction

 paste("on the ", counter, "rd count: ", k, sep="") 

You need to be a little smart to choose the correct suffix for the digit (i.e., "rd" after 3, "th" after 4-9, etc. There is a function here:

 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 space between the lines.

+12
source

Here is a slightly different approach to linking each whole to it with the corresponding suffix. If you select it separately, you will see that it captures a syntactic (?) Rule for constructing the ordinal form of each integer.

 suffixPicker <- function(x) { suffix <- c("st", "nd", "rd", rep("th", 17)) suffix[((x-1) %% 10 + 1) + 10*(((x %% 100) %/% 10) == 1)] } ## Testing with your example counter <- 3 k <- 9999 paste("on the ", paste0(counter, suffixPicker(counter)), " count: ", k, sep="") # [1] "on the 3rd count: 9999" ## Show that it also works for a range of numbers x <- 1:24 paste0(x, suffixPicker(x)) # [1] "1st" "2nd" "3rd" "4th" "5th" "6th" "7th" "8th" "9th" "10th" # [11] "11th" "12th" "13th" "14th" "15th" "16th" "17th" "18th" "19th" "20th" # [21] "21st" "22nd" "23rd" "24th" 

One explanatory note: bit 10*(((x %% 100) %/% 10) == 1) needed to select numbers ending in 10-19 (11, 12 and 13 are real bad actors here), sending them to everyone suffix elements containing "th" .

+2
source

Use sprintf

 > sprintf("on the %drd count: %d", counter, k) [1] "on the 3rd count: 9999" 
+1
source

All Articles