How to convert a string to an object name?

Is there any easier/tidier way to convert a string to an object name?

This is an (over)simplified version of what I want to achieve.

library(tidyverse)

df1 <- tibble(x = 1:3)
df2 <- tibble(x = 2:7, b = "bb")
dfs <- tribble(~df, "df1", "df2")

df_ncol <- function(df_name){ncol(eval(parse(text = df_name)))}

df_ncol("df1")
#> [1] 1


dfs %>% mutate(cols =  df_ncol(df))
#> # A tibble: 2 x 2
#>   df     cols
#>   <chr> <int>
#> 1 df1       2
#> 2 df2       2

The result is wrong as df1 has only 1 column (I assume that this solution is not vectorized).

Thank you.

I think you need a map function in your mutate. Perhaps

dfs %>% mutate(cols = map_dbl(df, df_ncol))

Thank you for your answer. The map function solves the use of non-vetorized functions.

But is there any tidy (eval) replacement for the eval(parse(text = )) ?

I'm not sure if this is the "right" way or even a good thing to do, but...

library(tidyverse)

df_ncol = function(df_name) {
  ncol(eval(sym(df_name)))
}

sym turns the string into a name and eval evaluates it. You could use base as.name instead of sym.

The function is not vectorized, but you can vectorize it with:

df_ncol = Vectorize(df_ncol)

Then...

df_ncol("df1")
#> df1 
#>   1


dfs %>% mutate(cols =  df_ncol(df))
#> # A tibble: 2 x 2
#>   df     cols
#>   <chr> <int>
#> 1 df1       1
#> 2 df2       2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.