Open In App

How to Print String and Variable on Same Line in R

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Printing a string and a variable on the same line is useful for improving readability, concatenating dynamic output, aiding in debugging by displaying variable values, and formatting output for reports or user display.

Below are different approaches to printing String and Variable on the Same Line using R Programming Language.

Table of Content

Printing a string and a variable on the same line Using paste() function

paste() is a function in R that is used for concatenating strings. paste() function can concatenate multiple arguments into a single character vector.

Syntax:

paste(..., sep = " ")

sep : A character string to separate the concatenated elements.

This example prints the string and variable on the same line using paste() funtion.

R
# Define variables
est <- 2008
founder <- "Sandeep Jain"

# Concatenate strings and variables using paste()
paste("GeeksforGeeks was founded in", est, "by", founder)

Output:

[1] "GeeksforGeeks was founded in 2008 by Sandeep Jain"

Printing a string and a variable on the same line Using sprintf() function

sprintf() in R is a function used for formatting strings. sprintf() allows us to create strings with placeholders that can be replaced by specified values. This function is similar to printf() in C programming.

Syntax:

sprintf(fmt)

fmt: A character string that specifies the format.

Below example shows how we can uses sprintf() function to print String and Variable on Same Line.

R
# Assigning values to variables
est <- 2008
founder <- "Sandeep Jain"

# Using sprintf to format a string
sprintf("GeeksforGeeks is a computer science portal founded by %s in %d", founder, est)

Output:

[1] "GeeksforGeeks is a computer science portal founded by Sandeep Jain in 2008"

Printing a string and a variable on the same line Using cat() function

In this approach we will use the cat() function in R which is used to concatenate and print its arguments.

This example uses cat() function to concatenates string and variables.

R
# Define a variable
name <- "Yuvraj"
age <- 22

# Print a string and the variable on the same line using cat
cat("My name is", name, "And i am ", age, "years old")

Output:

My name is Yuvraj And i am  22 years old

Conclusion

We seen several approaches to print a string and a variable on the same line, Each approach has its advantages, such as simplicity, flexibility, or formatting options. Choose the one that best suits for printing strings and variables together in R.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads