Mastering Text Output in R: From Basics to Advanced Techniques

Decorated and painted window frames of rock dwellings at Zelve.

Character vectors in R are used to store text data. R also provides a variety of built-in functions to deal with character vectors. Perhaps the most basic thing we can do with texts is to view them. R provides several ways to view texts in the console.

In this article, we will look at some handy functions that are used to concatenate (join) and print text output. We will learn:

  • Basic print function
  • concatenate string using cat function
  • concatenate string using paste function
  • The most flexible sprintf function, which is derived from C language

`Let’s get started!

The simplest way is to directly type the string in quotation marks:

"Hello"

We can also print a string value stored in a variable by simply evaluating it:

str1 <- "Hello"
str1

[1] "Hello"

If we want to explicitly print an object, we can use print() function.

# print string with quotes
print(str1)

[1] "Hello"

# print string without quotes
print(str1,quote=FALSE)

[1] Hello

An alternative to printing a string without quotes is to use noquote() function.

noquote("Hello")

[1] Hello

In some cases, we want the texts to appear as a message rather than a character vector with indices. In such cases, we use cat() function. cat does not print the numeric line indicator. As a result cat can be useful for printing nicely formatted responses to users.

cat("Hello")

Hello

cat() function allows us to concatenate (join) objects in a more flexible way.

name <- "siddharth"
language <- "R"
cat("Hello",name,"- a user of",language)

Hello siddharth - a user of R

When strings are combined together using cat function, the space character is used by default as the separator between the strings.
We can change it by specifying sep= argument. In the following example, we will use “_” as string separator.

cat("Hello",name,"- a user of",language,sep="_")

Hello_siddharth_- a user of_R

We can also use paste() function to concatenate several character vectors together. This function also uses space as the default separator.

paste("Hello","World")
[1] "Hello World"

paste("Hello","World",sep="_")
[1] "Hello_World"

If we don’t want separator, we can set sep = “” or alternatively call paste0() function.

paste("Hello","World",sep = "")
[1] "HelloWorld"

paste0("Hello","World")
[1] "HelloWorld"

Although both functions concatenate strings, the difference is that cat() only prints the string to the console, but paste()returns the string for further uses. The following code demonstrates that cat() prints the concatenated string but returns NULL

value1 <- cat("Hello","World")
"Hello","World"

value1
NULL

The previous examples show the behavior of paste() working with single-element character vectors. How paste function works with multi-element character vectors?

paste(c("A","B"),c("C","D"))

[1] "A C" "B D"

We can see, paste works element-wise, that is, paste(“A”,”C”) first, then paste(“B”,”D”), and finally, the results are collected to build a character vector of two elements.

If we want the results to be put together in one string, we can specify how these two elements are again concatenated by setting collapse=

paste(c("A","B"),c("C","D"),collapse = ",")
[1] "A C,B D"

If we want to put them in two lines, we can set collapse="\n"

result <- paste(c("A","B"),c("C","D"),collapse = "\n")
result

[1] "A C\nB D"

The new character vector result is a two-lined string, but the text representation of it is still written in one line. The new line is represented by \n as we specified.
To view the text we created, we need to call cat() function

cat(result)

A C
B D

sprintf() is useful printing function for precise control of the output. It returns a character vector containing a formatted combination of text and variable values. The function uses following placeholders to represent the input arguments to appear in the string.

  • %s for strings
  • %d for integers
  • %f for floating point number
  • %e for exponential notation

Substitute single string:

x <- "print string"
y <- "in R"

sprintf("Learning to %s in R", x)
[1] "Learning to print string in R"

Substitute multiple string:

sprintf("Learning to %s %s", x,y)
[1] "Learning to print string in R"

Print integer

version <- 3
sprintf("This is R version:%d", version)
[1] "This is R version:3"

Print integer with leading spaces

sprintf("This is R version:%3d", version)
[1] "This is R version:  3"

Print integer with leading zeros

sprintf("This is R version:%03d", version)
[1] "This is R version:003"

Print number with fixed point decimal notation

sprintf("This is R version:%f",pi)
[1] "This is R version:3.141593"

Print number with 3 decimal digits

sprintf("This is R version:%.3f",pi)
[1] "This is R version:3.142"

sprintf("%e",pi)
[1] "3.141593e+00"

In this article we explored various methods of printing text output in R. In particular, we learned:

  • print function to explicitly print an object
  • cat function to combine multiple strings
  • paste function to combine multiple strings. We also looked at subtle difference between paste and cat function
  • sprintf function for precise control of the output

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top