Home » How to Print String and Variable on Same Line in R

How to Print String and Variable on Same Line in R

by Erma Khan

Often you may want to print a a string and a variable on the same line in R.

Fortunately this is easy to do using the print() and paste0() functions.

The following example shows how to do so.

Example: Print String and Variable on Same Line in R

The following code shows how to print a string and a variable on the same line in R:

#define variable
my_variable #print string and variable on same line
print(paste0("The value of my variable is ", my_variable))

[1] "The value of my variable is 540.38"

Note that you can use the paste() and paste0() functions in R to concatenate multiple objects into a single string.

The paste() function concatenates strings using a space as the default separator.

The paste0() function concatenates strings using no space as the default separator.

Thus, if we instead used paste() then there would be an extra space in the final string:

#define variable
my_variable 

#print string and variable on same line
print(paste("The value of my variable is ", my_variable))

[1] "The value of my variable is  540.38"

Notice that there is an extra space in the final string.

Also note that we can use similar syntax to print multiple variables on the same line:

#define variables
var1 
#print string and multiple variables on same line
print(paste0("The first variable is ", var1, " and the second is ", var2))

[1] "The first variable is 540.38 and the second is 122"

Notice that the string and both variables are printed on the same line.

Additional Resources

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

How to Print Tables in R
How to Print All Rows of a Tibble in R
How to Use sprintf Function in R to Print Formatted Strings

Related Posts