对 R 中向量的不同元素应用不同的函数 [英] apply different functions to different elements of a vector in R
问题描述
申请很容易,但这对我来说是一个简而言之:
apply is easy, but this is a nutshell for me to crack:
在多参数回归中,优化器用于找到参数函数的最佳拟合,例如 x1,x2 数据.通常,如果优化器尝试优化转换参数(例如,使用 R 优化器,如 DEoptim、nls.lm),并且特定于函数的优化器会更快根据我的经验,对来自一个参数函数的不同参数进行不同变换会更好.
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.
我希望将 x.trans 中的不同函数(参见下文)应用于 x.val 中不同但在其位置对应的元素:
I wish to apply different functions in x.trans (c.f. below) to different but in their position corresponding elements in x.val:
可以使用的模拟示例.
#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]
...
有什么想法吗?(我尝试过 apply 和 sapply 但无法获取存储在 x.trans 中的函数)
Any ideas? (I have tried with apply, and sapply but can't get at the functions stored in x.trans)
推荐答案
你必须改用这个:
x.trans <- c(log10,exp,log10,function(x)x^2,function(x)1/x)
那么:
mapply(function(f, x) f(x), x.trans, x.val)
这篇关于对 R 中向量的不同元素应用不同的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!