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)

FAQs

How to print a value in R? ›

Print values on R console or file using cat() or print()

function can be used to print the argument. Print also returns the argument so it can be assigned. The “digits” argument specify the number of digits that should be displayed.

How to print numeric value in R? ›

R Print Output
  1. # print values. print("R is fun") # print variables x <- "Welcome to Programiz" ...
  2. # sprintf() with integer variable myInteger <- 123. sprintf("Integer Value: %d", myInteger) # sprintf() with float variable myFloat <- 12.34. ...
  3. # print using Cat. cat("R Tutorials\n")

How do I print results in R? ›

One of the most fundamental ways to display output in R is by employing the print() function. It is versatile and can display various data types, such as vectors, matrices, data frames, etc.

How do I print text with a variable in R? ›

Print output using paste() function inside print() function

R provides a method paste() to print output with string and variable together. This method defined inside the print() function. paste() converts its arguments to character strings. One can also use paste0() method.

Is there a print function in R? ›

However, R does have a print() function available if you want to use it. This might be useful if you are familiar with other programming languages, such as Python, which often uses the print() function to output code.

How to print variable name and value in R? ›

We can also print it by typing the name of the variable and hitting enter. In general, R will print to the console any object returned by a function or operation unless we assign it to a variable. Examples of valid variables names: hello , hello_there , hello. there , value1 .

How do I make a value numeric in R? ›

Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as. numeric().

How to print a list in R? ›

The elements of the list, like all arguments to a function, are separated by commas. As with previous variable types, you can print lists by passing their name to the print() function. Edit the list so that it has some more items in it. Try adding some different data types and even rearranging the items.

How do I print numbers on the same line in R? ›

You can use the cat() function to easily print multiple variables on the same line in R. This function uses the following basic syntax: cat(variable1, variable2, variable3, ...) The following examples show how to use this syntax in different scenarios.

How do I print in R mode? ›

R does not have a standard in-built function to calculate mode. So we create a user function to calculate mode of a data set in R. This function takes the vector as input and gives the mode value as output.

How to print elements of a vector in R? ›

R
  1. while (index <= length(vector)) { ... } : This line starts a while loop. ...
  2. print(vector[index]) : Inside the loop, this line prints the element of the vector at the current index .
  3. index <- index + 1 : After printing the element, this line increments the index by 1.
Sep 25, 2023

How do I print text with a variable? ›

To combine both text and a variable, use the + character:
  1. ExampleGet your own Java Server. String name = "John"; System. out. println("Hello " + name); ...
  2. Example. String firstName = "John "; String lastName = "Doe"; String fullName = firstName + lastName; System. out. ...
  3. Example. int x = 5; int y = 6; System. out.

How to print variable value in command line? ›

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

What is %>% in R? ›

R pipes are a way to chain multiple operations together in a concise and expressive way. They are represented by the %>% operator, which takes the output of the expression on its left and passes it as the first argument to the function on its right. Using pipes in R allows us to link a sequence of analysis steps.

Is there printf in R? ›

R comes with the sprintf() function that provides string formatting like in the C language. To be more precise, this function is a wrapper for the C library function of the same name. In many other programming languages, this type of printing is known as printf which stands for print formatting.

How to print in single line in R? ›

How to Print String and Variable on Same Line in R
  1. Using paste0() function.
  2. Using sprintf() function.
  3. Using cat() function.
Mar 19, 2024

References

Top Articles
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 5953

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.