Printing values in R (2024)

HOME R INTRODUCTION PRINT R

R introduction R basics

Printing values in R (1)

You can print values in R by entering a variable or object on the console or by using the print, sprintf and cat functions. In this tutorial you will learn how to print values in R in different situations.

print function

The print function prints objects on the R console. This function is really useful when you want the code to print some variable, message or object when a code is evaluated, when you want to print some result for debugging purposes or when you to check the current iteration of a for loop printing it on console.

As an example, you can input a string to the print function in order to print a message on console.

# Print a messageprint("This is a sample print")
[1] "This is a sample print"

You can also print variables and objects and the print function will use the corresponding method to print each type of object. Note that you can also print an object or variable by typing it on the R console.

# Print a variablex <- sqrt(18)print(x)# Note that this is equivalent to:# x
[1] 4.242641

Nonetheless, the print function allows you to customize the output. For instance, you can use the digits argument to set the desired number of digits.

# Print a variablex <- sqrt(18)print(x, digits = 3)
[1] 4.24

The print function can be used together with the paste or paste0 functions. In the following example we are printing the current iteration of a for loop.

# Print iterations of a loopfor(i in 1:5) { print(paste("Iteration:", i)) }
[1] "Iteration: 1"[1] "Iteration: 2"[1] "Iteration: 3"[1] "Iteration: 4"[1] "Iteration: 5"

In order to print a variable or object you don’t really need to use print, as you can just type the name of the variable or object on the console and press enter to print it.

You can print strings, variables, tables, data frames, lists, matrices and any other object with the print function.

Concatenate and print with cat

The cat function concatenates and prints objects without quotes. This function differs from print in many aspects, as it allows you to input several objects but only atomic vectors are allowed. This function also allows you to output values to a file.

cat("One", "Two", "Three")
One Two Three

Note that by default the function separates the objects with an empty space, but you can customize this specifying a new separator with sep.

cat("One", "Two", "Three", sep = "-")
One-Two-Three

If you want the objects to appear on a new line you can use "\n" as separator.

cat("One", "Two", "Three", sep = "\n")
OneTwoThree

Other interesting difference about print and cat is how each function handles a "\n" inside the string to be printed. While cat adds a new line, the print function prints the result ‘as is’.

cat("One\nTwo")print("One\nTwo")
OneTwo[1] "One\nTwo"

You can also use the cat function together with the paste or paste0 functions to print a single object.

# Variablex <- "https://r-charts.com/"# Printcat(paste0("Find R graph tutorials on ", x))
Find R graph tutorials on https://r-charts.com/

Output values into a file with sink

The cat function is useful to write files, as it provides an argument named file to specify the desired output file. You can also append values to the specified file setting append = TRUE.

# Write a file named file.csvcat(paste0(1:5, "A"), file = "file.csv", sep = "\n")# Append new values to file.csvcat(paste0(1:5, "B"), file = "file.csv", sep = "\n", append = TRUE)
1A2A3A4A5A1B2B3B4B5B

However, an alternative is to use the sink function to create a file and send all the prints to that file. You will also need to call sink() to close the connection.

# Create a filesink(file = "file.txt")# Output valuesx <- 3cat(paste0("The value is ", x), sep = "\n")cat("Text on new line")# Close connectionsink()closeAllConnections()
The value is 3Text on new line

Print without quotes with noquote

By default, if you print character values they will be shown with quotes, as in the example below.

print("R CODER")
"R CODER"

However, in R there is a function named noquote that removes the quotes from the output. Note that this function is equivalent to print(x, quote = FALSE).

noquote("R CODER")# Equivalent to:# print("R CODER", quote = FALSE)
R CODER

sprintf function

The sprintf function is a wrapper of the C function of the same name. It returns a formatted strings based on conversion specifications (see the table below for clarification). For strings you can use %s as shown in the following example.

x <- "R CODER"sprintf("The name of this site is %s", x)
[1] "The name of this site is R CODER"

You can also add more variables to sprintf and each value will be formatted depending on the corresponding conversion specification.

x <- "Peter"y <- 25sprintf("His name is %s and he is %d years old", x, y)
"His name is Peter and he is 25 years old

One of the most used conversions is %f to specify the desired number of decimal points (6 by default). In the next example we are setting two decimal points to the value.

value <- 10sprintf("This is the value with two decimal points: %0.2f", value)
"This is the value with two decimal points: 10.00"

The following table summarizes the conversion specifications available in R and its meaning.

Conversion specificationMeaning
%aDouble precision value (lower case)
%ADouble precision value (upper case)
%dInteger value
%iInteger value
%fDouble precision value, in “fixed point”
%eDouble precision value, in “exponential”
%EDouble precision value, in “exponential”
%gDouble precision value
%GDouble precision value
%oInteger value (octal)
%sCharacter string
%xInteger value (hexadecimal)
%XInteger value (hexadecimal)
Printing values in R (2024)
Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6700

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.