Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply different functions to different elements of a vector in R

apply is easy, but this is a nutshell for me to crack:

In multi-parametric regression, optimisers are used to find a best fit of a parametric function to say x1,x2 Data. Often, and function specific, optimisers can be faster if they try to optimise transformed parameters (e.g. with R optimisers such as DEoptim, nls.lm) From experience I know, that different transformations for different parameters from one parametric function is even better.

I wish to apply different functions in x.trans (c.f. below) to different but in their position corresponding elements in x.val:

A mock example to work with.

#initialise
x.val <- rep(100,5);      EDIT: ignore this part ==>  names(x.val) <- x.names
x.select <- c(1,0,0,1,1)
x.trans <- c(log10(x),exp(x),log10(x),x^2,1/x)

#select required elements, and corresponding names
x.val = subset(x.val, x.select == 1)
x.trans = subset(x.trans, x.select == 1)

# How I tried: apply function in x.trans[i] to x.val[i]
...

Any ideas? (I have tried with apply, and sapply but can't get at the functions stored in x.trans)

like image 864
Toby Avatar asked Dec 21 '22 03:12

Toby


1 Answers

You must use this instead:

x.trans <- c(log10,exp,log10,function(x)x^2,function(x)1/x)

Then this:

mapply(function(f, x) f(x), x.trans, x.val)
like image 190
Ferdinand.kraft Avatar answered Dec 22 '22 17:12

Ferdinand.kraft