Search code examples
rtidyversetibblerlang

How to pass tibble of variable names and function calls to tibble


I'm trying to go from a tibble of variable names and functions like this:

N <- 100
dat <- 
tibble(
  variable_name = c("a", "b"),
  variable_value = c("rnorm(N)", "rnorm(N)")
)

to a tibble with two variables a and b of length N

dat2 <-
  tibble(
    a = rnorm(N),
    b = rnorm(N)
  )

is there a !!! or rlang-y way to accomplish this?


Solution

  • We can evalutate the string

    library(dplyr)
    library(purrr)
    library(tibble)
    deframe(dat) %>%
          map_dfc(~ eval(rlang::parse_expr(.x)))
    

    -output

    # A tibble: 100 x 2
             a       b
         <dbl>   <dbl>
     1  0.0750  2.55  
     2 -1.65   -1.48  
     3  1.77   -0.627 
     4  0.766  -0.0411
     5  0.832   0.200 
     6 -1.91   -0.533 
     7 -0.0208 -0.266 
     8 -0.409   1.08  
     9 -1.38   -0.181 
    10  0.727   0.252 
    # … with 90 more rows