4

I would like to transform c('1','2', 'text') into a character vector with only one elemenent c('1','2', 'text').

I have tried this:

> quote(c('1','2', 'text'))
c("1", "2", "text")

but

> class(quote(c('1','2', 'text')))
[1] "call"

and this:

> toString(quote(c('1','2', 'text')))
[1] "c, 1, 2, text"

which removes all the punctuation (while I would like to keep the exact same string).

0

2 Answers 2

9

deparse is for converting expressions to character strings.

deparse(c('1','2', 'text'))
#[1] "c(\"1\", \"2\", \"text\")"

cat(deparse(c('1','2', 'text')))
#c("1", "2", "text")

gsub("\"", "'", deparse(c('1','2', 'text')))
#[1] "c('1', '2', 'text')"

deparse(quote(c('1','2', 'text')))
#[1] "c(\"1\", \"2\", \"text\")"

Also look at substitute

deparse(substitute(c(1L, 2L)))
#[1] "c(1L, 2L)"
Sign up to request clarification or add additional context in comments.

4 Comments

using cat and deparse together was a smart one.
Thanks. I definitely works with my example, but not with this gsub("\"", "'", deparse(c(1L ,2L)))
@d.b that returns [1] "c('1', '2')" while I would expect [1] "c(1L, 2L)"
Thanks, seems to me that gsub("\"", "'", deparse(substitute(c(1L, 2L)))) is the most generalizable then (in my original code I have a bunch of different vectors).
2

You could try this :

  convert_vecteur <- function(vector){
    if(is.numeric(vector)){
      char<- paste0("c(",paste(vector,collapse = ","),")")
    } else {
      char <- paste0("c('",paste(vector,collapse = "','"),"')")
    }
    return(char)
  }

  convert_vecteur(c('1','2', 'text'))
  #[1] "c('1', '2', 'text')"
  cat(convert_vecteur(c('1','2', 'text')))
  # c('1', '2', 'text')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.