1

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?

deschen
  • 10,012
  • 3
  • 27
  • 50
  • 2
    Use `get`: `eval(parse(text = get(paste0(question_stem, "_my_vector"))))` – GKi Oct 05 '21 at 11:52
  • Ah, get! Thanks, works perfectly fine. If you want to turn it into ans answer, I gladly accept (although I suspect that such an easy answer indicates that my question is probably a duplicate). – deschen Oct 05 '21 at 11:55
  • I am not sure but maybe this https://stackoverflow.com/questions/9083907/how-to-call-an-object-with-the-character-variable-of-the-same-name ? – Ronak Shah Oct 05 '21 at 12:07
  • Yep, `get´ was the solution. – deschen Oct 05 '21 at 12:42

2 Answers2

1

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
GKi
  • 37,245
  • 2
  • 26
  • 48
0

We can use str_extract

library(stringr)
 str_extract_all(get(paste0(question_stem, "_my_vector")), '(?<=")[^",)]+')[[1]]
[1] "Element 1" "Element 2" "Element 3" "Element 4"
akrun
  • 874,273
  • 37
  • 540
  • 662