rlistpurrrrlanglambda-calculus

Execute a list of purrr-style lambda formulas on a data frame


The following toy data has 5 variables, X1 to X5.

set.seed(123)
df <- data.frame(matrix(rnorm(500), 100, 5))

I want to perform specific operations on specific variables, using a named list of purrr-style lambda formulas

fun_list <- list(
  X2 = ~ quantile(.x, c(0.1, 0.9), na.rm = TRUE),
  X4 = ~ fivenum(.x, na.rm = TRUE)
)

How can I apply fun_list to my df according to its variable names?

I know rlang::as_function() can convert a purrr-style formula into a R function. But I guess there is some function that is able to deal with purrr-style formulas intrinsically. Its usage might be

execute(fun_list, environment = df)

The expected output is

$X2
      10%       90% 
-1.289408  1.058432 

$X4
[1] -2.465898194 -0.737146704 -0.003508661  0.693634712  2.571458146

Solution

  • A workaround is to use a nested map, which can take a purrr-style formula as input and avoid the use of rlang::as_function().

    library(purrr)
    
    imap(fun_list, \(f, var) map(df[var], f)[[1]])
    
    # $X2
    #       10%       90% 
    # -1.289408  1.058432 
    # 
    # $X4
    # [1] -2.465898194 -0.737146704 -0.003508661  0.693634712  2.571458146
    

    or briefly, imap(fun_list, ~ map(df[.y], .x)[[1]]).