Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate String and an output evaluated from a function in R?

Tags:

r

statistics

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.

like image 972
user1769197 Avatar asked Oct 23 '12 18:10

user1769197


2 Answers

Use sprintf

> sprintf("on the %drd count: %d", counter, k)
[1] "on the 3rd count: 9999"
like image 156
GSee Avatar answered Oct 15 '22 02:10

GSee


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.

like image 25
Drew Steen Avatar answered Oct 15 '22 01:10

Drew Steen