Search code examples
rrlang

How to create a data.frame from expression?


I want to create a data frame from an expression saved into an object.

Whereas this works:

library(dplyr)

regular_chr_vec <- c(a = "lion", b = "zebra")
bind_rows(regular_chr_vec)

##   a     b    
##   <chr> <chr>
## 1 lion  zebra

This doesn't:

library(rlang)

as_expression_vec <- parse_expr("c(a = \"lion\", b = \"zebra\")")
bind_rows(!!!as_expression_vec)

Error: Argument 1 must be a data frame or a named atomic vector.

Nor this:

as_expression_vec <- parse_expr("c(a = \"lion\", b = \"zebra\")")
bind_rows(!!as_expression_vec)

Error: Can't use !! in a non-quoting function


So my question is: How can I create a dataframe if I'm just handed with as_expression_vec?

##   a     b    
##   <chr> <chr>
## 1 lion  zebra

I intentionally kept the question minimal and with no context to not distract the point. Thanks!


Solution

  • Here is one solution

    library(rland)
    library(dplyr)
    
    as_expression_vec <- parse_expr("c(a = \"lion\", b = \"zebra\")")
    
    bind_rows(eval(as_expression_vec))
    
    # A tibble: 1 x 2
      a     b    
      <chr> <chr>
    1 lion  zebra