Print string and variable contents on the same line in R
RPrintingR Problem Overview
Is there a way to print text and variable contents on the same line? For example,
wd <- getwd()
print("Current working dir: ", wd)
I couldn't find anything about the syntax that would allow me to do this.
R Solutions
Solution 1 - R
You can use paste
with print
print(paste0("Current working dir: ", wd))
or cat
cat("Current working dir: ", wd)
Solution 2 - R
> {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))
Solution 3 - R
Or using message
message("Current working dir: ", wd)
@agstudy's answer is the more suitable here
Solution 4 - R
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()
Solution 5 - R
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()
.
Solution 6 - R
As other users said, cat() is probably the best option.
@krlmlr suggested using sprintf() and it's currently the third ranked answer. sprintf() is not a good idea. From R documentation:
>The format string is passed down the OS's sprintf function, and incorrect formats can cause the latter to crash the R process.
There is no good reason to use sprintf() over cat or other options.
Solution 7 - R
you can use paste0 or cat method to combine string with variable values in R
For Example:
paste0("Value of A : ", a)
cat("Value of A : ", a)
Solution 8 - R
A trick would be to include your piece of code into ()
like this:
(wd <- getwd())
which means that the current working directory is assigned to wd
and then printed.