How to print multiple variables on the same line in R?

In R, you can print multiple variables on the same line using the paste() function, which combines strings and variables together. You can also use the sprintf() function to format the output. The cat() function can then be used to print the result to the console.


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.

Example 1: Print Character String & Variable on Same Line

The following code shows how to use the cat() function to print a character string and several numeric variables on the same line:

#define character string
my_text <- "The answer is"

#define numeric variables
my_value1 <- 5
my_value2 <- 10

#print character string and numeric variables on the same line
cat(my_text, my_value1, "or", my_value2)

The answer is 5 or 10

Each of the variables are printed on the same line.

Example 2: Print Multiple Variables on Same Line with No Text

The following code shows how print several variables from some function on the same line without any text:

#define function
do_stuff <- function(x) {
    x2 <- x * 2
    x3 <- x * 3
    x4 <- x * 4
    cat(x2, x3, x4)
}

#use function
do_stuff(5)

10 15 20

The function returns all three numeric variables on the same line without any text explaining which variable names correspond to each value.

Example 3: Print Multiple Variables on Same Line with Text

The following code shows how print several variables from some function on the same line with text:

#define function
do_stuff <- function(x) {
    x2 <- x * 2
    x3 <- x * 3
    x4 <- x * 4
    cat("x2 =", x2, "x3 =", x3, "x4 =", x4)
}

#use function
do_stuff(5)

x2 = 10 x3 = 15 x4 = 20

The function returns all three numeric variables on the same line with text explaining which variable names correspond to each value.

Example 4: Print Multiple Variables on New Lines with Text

#define function
do_stuff <- function(x) {
    x2 <- x * 2
    x3 <- x * 3
    x4 <- x * 4
    cat("x2 =", x2, "nx3 =", x3, "nx4 =", x4)
}

#use function
do_stuff(5)

x2 = 10 
x3 = 15 
x4 = 20

The function returns all three variables on different lines with text explaining which variable names correspond to each value.

The following tutorials explain how to perform other common operations in R:

x