rtostring

Using toString function in R


I have numeric objects a=1,b=2,c=3,d=4. Now when I use :

toString(c(a,b,c,d))

I get:

"1, 2, 3, 4"

as the output. How do I get rid of the comma? I want "1234" as the output. Or is there another way to do this?


Solution

  • Just use paste or paste0:

    a <- 1; b <- 2; c <- 3; d <- 4
    paste0(a, b, c, d)
    # [1] "1234"
    paste(a, b, c, d, sep="")
    # [1] "1234"
    

    You cannot get the result directly from toString even though toString uses paste under the hood:

    toString.default
    # function (x, width = NULL, ...) 
    # {
    #     string <- paste(x, collapse = ", ")
    # --- function continues ---
    

    Compare that behavior with:

    paste(c(a, b, c, d), collapse = ", ")
    # [1] "1, 2, 3, 4"
    

    Since it is hard-coded, if you really wanted to use toString, you would have to then use sub/gsub to remove the "," after you used toString, but that seems inefficient to me.