[R] make elements of a list into functions
Uwe Ligges
ligges at statistik.tu-dortmund.de
Wed Mar 25 01:20:36 CET 2015
On 25.03.2015 00:38, Kruti Pandya wrote:
> Hi I have a list called g as follows and I want to make elements of g into
> functions so that I can evaluate them at randomly generated data point say
> c(0,0,0). For example,
>
> change g[[1]] (!x[2] & !x[3]) | (!x[2] & x[3]) | (x[2] & x[3]) to
> function(x) (!x[2] & !x[3]) | (!x[2] & x[3]) | (x[2] & x[3])
>
> change g[[2]] (!x[2] & !x[1]) | (!x[2] & x[1]) | (x[2] & !x[1]) to
> function(x) (!x[2] & !x[1]) | (!x[2] & x[1]) | (x[2] & !x[1])
>
> and so on......
>
> So that I can evaluate g[[1]] as follows g1<-function(x) (!x[2] & !x[3]) |
> (!x[2] & x[3]) | (x[2] & x[3])
One way:
f <- function(x) x
gfunc <- lapply(g, function(i) {body(f) <- parse(text=i); f})
So now you have functions in your list gfunc and can call them via
gfunc[[1]](c(0,0,0))
Best,
Uwe Ligges
>
>> g1(c(0,0,0))
> [1] TRUE
>
> g<-list(structure("(!x[2] & !x[3]) | (!x[2] & x[3]) | (x[2] & x[3])", class
> = "noquote"),
> structure("(!x[2] & !x[1]) | (!x[2] & x[1]) | (x[2] & !x[1])",
> class = "noquote"),
> structure("(!x[2] & x[3]) | (x[2] & !x[3])", class = "noquote"))
>
> g
> [[1]]
> [1] (!x[2] & !x[3]) | (!x[2] & x[3]) | (x[2] & x[3])
>
> [[2]]
> [1] (!x[2] & !x[1]) | (!x[2] & x[1]) | (x[2] & !x[1])
>
> [[3]]
> [1] (!x[2] & x[3]) | (x[2] & !x[3])
>
> Do not know how proceed. Any help is appreciated. I have created a small
> example for demo. My actual list g has 50 elements so need a function which
> can pick each element of g and convert it into function (x)......
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list