apply different functions to different elements of a vector in R

你说的曾经没有我的故事 提交于 2019-11-30 18:03:45

问题


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)


回答1:


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)


来源:https://stackoverflow.com/questions/17490297/apply-different-functions-to-different-elements-of-a-vector-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!