print in R: How to Print Variables in R

Every language provides some functions that can help you print the data on the console, and R is no different. To print the data on the console in R, use the print() function.

print in R

The print() is a built-in generic R function that prints its argument and returns it invisibly (via invisible()). It accepts three arguments and does not return any value. Instead, the print() method will print out the argument on the screen.

Syntax

print(data, digits, na.print)

Parameters

data: It specified the argument to be displayed.

digits: It defines the minimal number of significant digits.

na.print: It indicates NA values output format.

Example

Create a vector using the colon(:) operator.

data <- 1:5
print(data)

Output

[1] 1 2 3 4 5

Passing digits argument

The print() function accepts the digits argument, which will help us print the floating-point values.

data <- 1 / 5
data2 <- 111 / 23
data3 <- 10900 / 2966

print(data, digits = 2)
print(data2, digits = 3)
print(data3, digits = 4)

Output

[1] 0.2
[1] 4.83
[1] 3.675

Passing na.print argument to print() function

If you pass the na.print argument to empty, it will replace NA values with nothing in the output.

data <- matrix(c(21, NA, 46, 11, NA, 19),
               nrow = 3, byrow = TRUE)

print(data)
cat("After passing na.print argument to empty", "\n")
print(data, na.print = "")

Output

     [,1] [,2]
[1,]  21   NA
[2,]  46   11
[3,]  NA   19
After passing na.print argument to empty
     [,1] [,2]
[1,]  21
[2,]  46   11
[3,]       19

As you can see that in the output that after passing the na.print to empty, some values are disappeared completely from the matrix because we are telling R that replace NA values with nothing.

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

To concate strings in R, use the paste() function. We will define the paste() method inside the print() method.

data <- "Covid-19 "

print(paste(data, "is surging in India"))

Output

[1] "Covid-19 is surging in India"

That is it for print() function in R.

Leave a Comment