0

Program R

I want to create a function in R which would take the column names from a data frame and create a new function which argument names are the same as the column names, having as many arguments as there are columns.

my_function<-function(data_frame){

return(new_function<-function(#column_name_1,#column_name_2,#column_name3,#column_name_x){
[function does something cool]
}
)

}

For example, if I have a data frame:

> dimorphandra
     genus_species temp germinability waterpotential
1  Dimorphandra_mollis 30.8            86            0.0
2  Dimorphandra_mollis 32.5            94            0.0
3  Dimorphandra_mollis 35.0            74            0.0
4  Dimorphandra_mollis 37.0            44            0.0
5  Dimorphandra_mollis 39.0             2            0.0
6  Dimorphandra_mollis 41.0             0            0.0

Then I would apply my_function to it:

my_function(dimorphandra)

Which would output:

new_function<-function(genus_species,temp,germinability,water potential){

[function does something cool]

}

How can I create my_function?

Thank you very much!

  • 3
    you just want to change the default named arguments? `f <- function() {}; formals(f) <- setNames(vector('list', ncol(mtcars)), names(mtcars)); body(f) <- quote(print('simon says do something cool')); f()` – rawr Oct 20 '16 at 22:11
  • You could use `eval` : `genfun <- function(data) { args <- toString(names(data)); eval(parse(text = sprintf("function(%s) list(%s)", args, args))) }; genfun(iris)` – G. Grothendieck Oct 20 '16 at 22:19
  • 1
    For a nice answer that describes several ways to programatically construct a function, [see here](http://stackoverflow.com/a/12983961/980833). – Josh O'Brien Oct 20 '16 at 22:22
  • 3
    The previous comments are great but I'd recommend ignoring all of them and telling us *why* you want to do this. – Dason Oct 20 '16 at 22:43
  • @rawr, please post as answer? – Ben Bolker Oct 20 '16 at 23:00
  • Just read the source of the `scales` package. _Tons_ of examples. – hrbrmstr Oct 20 '16 at 23:57

0 Answers0