Reputation: 10996
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?
Upvotes: 1
Views: 292
Reputation: 887088
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"
Upvotes: 0
Reputation: 39657
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
Upvotes: 1