{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))
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()
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.
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()
.
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)
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.
Or using message
message("Current working dir: ", wd)
@agstudy's answer is the more suitable here
Source: Stackoverflow.com