3

In excel (and Excel VBA) it is really helpful to connect text and variable using "&":

a = 5
msgbox "The value is: " & a

will give

"The value is: 5"

How can I do this in R? I know there is a way to use "paste". However I wonder if there isn't any trick to do it as simple as in Excel VBA.

Thanks in advance.

Community
  • 1
  • 1
Bendaua
  • 331
  • 1
  • 2
  • 11

2 Answers2

5

This blog post suggests to define your own concatenation operator, which is similar to what VBA (and Javascript) has, but it retains the power of paste:

"%+%" <- function(...) paste0(..., sep = "")

"Concatenate hits " %+% "and this."
# [1] "Concatenate hits and this."

I am not a big fan of this solution though because it kind of obscures what paste does under the hood. For instance, is it intuitive to you that this would happen?

"Concatenate this string " %+% "with this vector: " %+% 1:3
# [1] "Concatenate this string with this vector: 1"
# [2] "Concatenate this string with this vector: 2"
# [3] "Concatenate this string with this vector: 3"

In Javascript for instance, this would give you Concatenate this string with this vector: 1,2,3, which is quite different. I cannot speak for Excel, but you should think about whether this solution is not more confusing to you than it is useful.

If you need Javascript-like solution, you can also try this:

"%+%" <- function(...) {
   dots = list(...)
   dots = rapply(dots, paste, collapse = ",")
   paste(dots, collapse = "")
}

"Concatenate this string " %+% "with this string."
# [1] "Concatenate this string with this string."

"Concatenate this string " %+% "with this vector: " %+% 1:3
# [1] "Concatenate this string with this vector: 1,2,3"

But I haven't tested extensively, so be on lookout for unexpected results.

jakub
  • 4,774
  • 4
  • 29
  • 46
1

Another possibility is to use sprintf:

a <- 5
cat(sprintf("The value is %d\n",a))
## The value is 5

the %d denotes integer formatting (%f would give "The value is 5.000000"). The \n denotes a newline at the end of the string.

sprintf() can be more convenient than paste or paste0 when you want to put together a lot of pieces, e.g.

sprintf("The value of a is %f (95% CI: {%f,%f})",
        a_est,a_lwr,a_upr)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453