简体   繁体   中英

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?

We can eval utate 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

Here is a base way with a pipe and a as_tibble call.

Map(function(x) eval(str2lang(x)), setNames(dat$variable_value, dat$variable_name)) %>%
  as_tibble

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM