Home > database >  How to correctly evaluate a literal character vector
How to correctly evaluate a literal character vector

Time:10-06

Let's assume I have the following object in R:

QXX_my_vector <- "c(\"Element 1\", \"Element 2\", \"Element 3\", \"Element 4\")"

I want to turn this into a true character vector containing the four elements.

I can do this via eval(parse(text = QXX_my_vector)) which gives:

# [1] "Element 1" "Element 2" "Element 3" "Element 4"

My problem/question is: I want to dynamically pass the text element into the parse function, i.e.:

question_stem = "QXX"
eval(parse(text = paste0(question_stem, "_my_vector")))

However, this gives:

# [1] "c(\"Element 1\", \"Element 2\", \"Element 3\", \"Element 3\")"

I also tried to wrap the paste0 part into a sym function, but this gives the same result.

Any ideas?

CodePudding user response:

You have to use get to get an object with the given name.

eval(parse(text = get(paste0(question_stem, "_my_vector"))))
#[1] "Element 1" "Element 2" "Element 3" "Element 4
  • Related