How do I appropriately use the backslash character in a string ? I would like to have this "The product of 4 and 2345 is 9380."
instead of "The product of 4 and 2345 is 9380 ."
I included the backslash character "\b"
before .
but it did not work out.
Here is the code:
my_function <- function(fname, lname) {
print(paste("The product of", fname, "and", lname, "is", fname*lname,"."))}
my_function(4,2345)
Many thanks.
CodePudding user response:
For readability of strings merged with variables, I recommend looking at the sprintf()
function.
val1 <- 4
val2 <- 2345
sprintf("The product of %s and %s is %s.", val1, val2, val1 * val2)
[1] "The product of 4 and 2345 is 9380."
CodePudding user response:
Another solution is to use paste0
which is equivalent to paste(..., sep="")
, but slightly more efficient.
my_function <- function(fname, lname) {
print(paste0("The product of ", fname, " and ", lname, " is ", fname*lname,"."))}
my_function(4,2345)
[1] "The product of 4 and 2345 is 9380."
CodePudding user response:
Use cat()
to print a string without encoding escape characters:
my_message <- function(a, b) {
paste("The product of", a, "and", b, "is", a * b, "\b.")
}
print(my_message(4, 2345))
#> [1] "The product of 4 and 2345 is 9380 \b."
cat(my_message(4, 2345), "\n")
#> The product of 4 and 2345 is 9380.
But likely in this case you wouldn’t want to use a backspace character. Instead, you’d avoid inserting the space in the first place, like other answers show.