Home > OS >  Storing functions in dataframe in R
Storing functions in dataframe in R

Time:05-10

I am doing some bayesian analysis and have empirical distributions for many features (that is, one distribution for each feature). I want to store the feature indices, their distribution functions and some other information in a data frame or a tibble, one row for each feature, for convenience of further usage.

But I think data.frame or tibble function in R won't allow functions as their input. Is there an alternative way to save those as a dataframe-type structure?

Thanks in advance!

CodePudding user response:

You can do store those functions as part of a data.table or tibble, like with this example:

data.table(id=c(1,2,3), dist_funcs = list(pnorm, ppois, pbinom))

Output:

      id    dist_funcs
   <num>        <list>
1:     1 <function[1]>
2:     2 <function[1]>
3:     3 <function[1]>

Similarly with tibbles:

tibble(id=c(1,2,3), dist_funcs = list(pnorm, ppois,pbinom))

Output:

     id dist_funcs
  <dbl> <list>    
1     1 <fn>      
2     2 <fn>      
3     3 <fn>  

CodePudding user response:

You can store functions in a list:

> list(mean, median)
[[1]]
function (x, ...) 
UseMethod("mean")
<bytecode: 0x000002b3fdfb77d0>
<environment: namespace:base>

[[2]]
function (x, na.rm = FALSE, ...) 
UseMethod("median")
<bytecode: 0x000002b3f95dd3f8>
<environment: namespace:stats>
  • Related