Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print string and variable contents on the same line in R

Tags:

r

printing

People also ask

How do you print a string and a variable together in R?

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.

How do I print two things 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, ...)

How do you print a string and int on the same line?

Use comma “,” to separate strings and variables while printing int and string in the same line in Python or convert the int to string.


You can use paste with print

print(paste0("Current working dir: ", wd))

or cat

cat("Current working dir: ", wd)

{glue} offers much better string interpolation, see my other answer. Also, as Dainis rightfully mentions, sprintf() is not without problems.

There's also sprintf():

sprintf("Current working dir: %s", wd)

To print to the console output, use cat() or message():

cat(sprintf("Current working dir: %s\n", wd))
message(sprintf("Current working dir: %s\n", wd))

Or using message

message("Current working dir: ", wd)

@agstudy's answer is the more suitable here


Easiest way to do this is to use paste()

> paste("Today is", date())
[1] "Today is Sat Feb 21 15:25:18 2015"

paste0() would result in the following:

> paste0("Today is", date())
[1] "Today isSat Feb 21 15:30:46 2015"

Notice there is no default seperator between the string and x. Using a space at the end of the string is a quick fix:

> paste0("Today is ", date())
[1] "Today is Sat Feb 21 15:32:17 2015"

Then combine either function with print()

> print(paste("This is", date()))
[1] "This is Sat Feb 21 15:34:23 2015"

Or

> print(paste0("This is ", date()))
[1] "This is Sat Feb 21 15:34:56 2015"

As other users have stated, you could also use cat()


The {glue} package offers string interpolation. In the example, {wd} is substituted with the contents of the variable. Complex expressions are also supported.

library(glue)

wd <- getwd()
glue("Current working dir: {wd}")
#> Current working dir: /tmp/RtmpteMv88/reprex46156826ee8c

Created on 2019-05-13 by the reprex package (v0.2.1)

Note how the printed output doesn't contain the [1] artifacts and the " quotes, for which other answers use cat().