Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using toString function in R

Tags:

r

tostring

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?

like image 228
Aman Mathur Avatar asked Jan 19 '14 06:01

Aman Mathur


People also ask

What is the function toString () method?

For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

How do I convert an object to a string in R?

toString() function in R Language is used to convert an object into a single character string.

How do I convert a string to a vector in R?

To convert elements of a Vector to Strings in R, use the toString() function. The toString() is an inbuilt R function used to produce a single character string describing an R object.


1 Answers

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.

like image 88
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 19 '22 00:09

A5C1D2H2I1M1N2O1R2T1