[R] Vector of functions
Joshua Wiley
jwiley.psych at gmail.com
Sat Jul 2 19:59:39 CEST 2011
Hi Thomas,
On Sat, Jul 2, 2011 at 9:36 AM, Thomas Stibor <thomas.stibor at in.tum.de> wrote:
> Hi there,
>
> I have a vector of some functions e.g.
> #-----------------------------#
> f.1 <- function(a) {
> return( a );
> }
> f.2 <- function(a) {
> return( 1 - (tanh(a))^2 );
> }
> f.3 <- function(a) {
> return( 1 / (1+exp(-a)) * (1 - (1 / (1+exp(-a)))) );
> }
>
> func.l <- c(f.1, f.2, f.3);
> #-----------------------------#
>
> and would like to calculate the output value of a function in the
> vector, that is, pick e.g. function at position 2 in func.l and calculate the
> output value for a=42.
>
> func.l[2](42); # gives error
Almost there, you just need to use a different extraction operator...
func.l[[2]](42)
compare the output of
func.l[2]
func.l[[2]]
the first one retains the list structure, but just returns a list with
the second element of func.l, the second one actually returns a
function. You can check this by looking at the class
class(func.l[2])
class(func.l[[2]])
Cheers,
Josh
>
> f <- func.l[2];
> f(42); # gives error
>
> Is there an easy way to solve this problem?
>
> Cheers,
> Thomas
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/
More information about the R-help
mailing list