Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Glue as an object

I’d like to use the output of the glue function as an R object, but it only works as character.

Example: if I try this –

as.factor((
  str_glue("iris$`{colnames(iris[5])}`")
))

The result is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1] iris$`Species`
Levels: iris$`Species`

But I want this:

as.factor(iris$`Species`)


[1] setosa     setosa     setosa     setosa     setosa     setosa     setosa     setosa     setosa    
 ...
[145] virginica  virginica  virginica  virginica  virginica  virginica 
Levels: setosa versicolor virginica

>Solution :

Use eval and parse or parse_expr:

my_str <- str_glue("iris$`{colnames(iris[5])}`")   # glue object

class(my_str)
[1] "glue"      "character"

eval(parse_expr(my_str)) %>% as.factor

[1] setosa     setosa     setosa     setosa     setosa     setosa     setosa     setosa     setosa    
 ...
[145] virginica  virginica  virginica  virginica  virginica  virginica 
Levels: setosa versicolor virginica
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading