Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to a string in R

Tags:

r

I have an integer

a <- (0:3)

And I would like to convert it to a character string that looks like this

b <- "(0:3)"

I have tried

as.character(a)
[1] "0" "1" "2" "3"

and

toString(a)
[1] "0, 1, 2, 3"

But neither do exactly what I need to do.

Can anyone help me get from a to b?

Many thanks in advance!

like image 588
Cristian Avatar asked Jun 08 '18 09:06

Cristian


2 Answers

paste0("(", min(a), ":", max(a), ")")
"(0:3)"

Or more concisely with sprintf():

sprintf("(%d:%d)", min(a), max(a))
like image 52
sindri_baldur Avatar answered Sep 28 '22 09:09

sindri_baldur


One option is deparse and paste the brackets

as.character(glue::glue('({deparse(a)})'))
#[1] "(0:3)"

Another option would be to store as a quosure and then convert it to character

library(rlang)
a <- quo((0:3))
quo_name(a)
#[1] "(0:3)"

it can be evaluated with eval_tidy

eval_tidy(a)
#[1] 0 1 2 3
like image 42
akrun Avatar answered Sep 28 '22 11:09

akrun