管理R中矢量化函数的输出 [英] Managing output of a Vectorized function in R
问题描述
我有一个 Vectorize
d函数,名为 vec
(如下)。我的目标是能够获得子表列表作为此函数的输出。也就是说,当我运行该函数时,我将能够将函数调用保存为一个对象(例如, I
),然后使用 $
从 I
,在这种情况下就像这样(首次运行函数 vec
下面):
code> I = vec(L = .3,U = .6,level = seq(.5,.95,.1 )); I $ alpha;我$ beta
使用 Vectorize
可能吗? (高度赞赏你的专业知识)
以下是R函数:
vec = Vectorize(函数(L,U,level = .95){
p1 =(1 - level)/ 2
p2 = 1 - p1
f.beta函数(alpha,beta,x,lower = 0,upper = 1){
p <-pbeta((x-lower)/(upper-lower),alpha, β)
log(p /(1-p))}
delta < - 函数(fit,actual)sum((fit-actual)^ 2)
目标函数(θ,x,prob,...){
ab < - exp(θ)
fit <-f.beta(ab [1],ab (函数(p)log(p /(1-p),...,b) ))(c(p1,p2))
sol <-nlm(objective,log(c(1e1,1e1)),x = c(L,U),prob = xp,lower = 0,upper = 1,typsize = c(1,1),fscale = 1e-12,gradtol = 1e-12)
parm < - as.numeric(exp(sol $ estimate) )
list(alpha = parm [[1]],beta = parm [[2]])
},c(L,U level),SIMPLIFY = FALSE)
该函数已经被矢量化了,但是输出在 list
中。所以,我们通过循环列表
元素来提取'alpha'和'beta'组件
sapply(I,'[[','alpha')
#[1] 2.371449 3.562465 5.278213 7.939884 12.918233
sapply(I,'[[','beta')
#[1] 2.863406 4.336959 6.461091 9.757192 15.922938
请注意,输出可以简化为矩阵with two row
simplify2array(I)
或两列矩阵
do.call(rbind,I)
I have a Vectorize
d function called vec
(below). My goal is to be able to get a subsetable list as the output from this function. That is, when I run the function, I will be able to save the function call as an object (e.g., I
) and then subset the desired output by using $
from I
, in this case like this (First run function vec
below):
I = vec(L = .3, U = .6, level = seq(.5, .95, .1)) ; I$alpha ; I$beta
Is this possible given the use of Vectorize
? (highly appreciate your expertise)
Here is the R function:
vec = Vectorize(function(L, U, level = .95){
p1 = (1 - level)/2
p2 = 1 - p1
f.beta <- function(alpha, beta, x, lower = 0, upper = 1){
p <- pbeta((x-lower)/(upper-lower), alpha, beta)
log(p/(1-p)) }
delta <- function(fit, actual) sum((fit-actual)^2)
objective <- function(theta, x, prob, ...) {
ab <- exp(theta)
fit <- f.beta(ab[1], ab[2], x, ...)
return (delta(fit, prob)) }
x.p <- (function(p) log(p/(1-p)))(c(p1, p2))
sol <- nlm(objective, log(c(1e1, 1e1)), x = c(L, U), prob = x.p, lower = 0, upper = 1, typsize = c(1, 1), fscale = 1e-12, gradtol = 1e-12)
parm <- as.numeric(exp(sol$estimate))
list(alpha = parm[[1]], beta = parm[[2]])
}, c("L", "U", "level"), SIMPLIFY = FALSE)
The function is already vectorized, but the output is in a list
. So, we loop through the list
elements to extract the 'alpha' and 'beta' components
sapply(I, '[[', 'alpha')
#[1] 2.371449 3.562465 5.278213 7.939884 12.918233
sapply(I, '[[', 'beta')
#[1] 2.863406 4.336959 6.461091 9.757192 15.922938
Note that the output can simplified to a matrix with two rows
simplify2array(I)
Or a two column matrix
do.call(rbind, I)
这篇关于管理R中矢量化函数的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!