【问题标题】:How to find the most optimum value for a function argument given a desired answer in R?给定 R 中所需的答案,如何找到函数参数的最佳值?
【发布时间】:2017-06-19 22:34:20
【问题描述】:

我想知道如何找到 t 的最精确值,因为我希望下面整个函数调用的答案在 R 中变为 3

if(!require(BayesFactor)){install.packages('BayesFactor')} ; library(BayesFactor)

# 3 = function call below:
unname(ttest.tstat( t, 20, 20, rscale = sqrt(2)/2, simple = TRUE)[[1]])

【问题讨论】:

  • 看看optim

标签: r function math linear-algebra equation


【解决方案1】:

这是一个使用 optim 的解决方案。 par 是使您最接近 3 的 t 值。其他方法可能会使您更接近,但那是在我的驾驶室之外。

library(BayesFactor)

f1 <- function(t){
  abs(ttest.tstat( t, 20, 20, rscale = sqrt(2)/2, simple = TRUE)[[1]]-3)
}

f2 <- function(t){
  ttest.tstat( t, 20, 20, rscale = sqrt(2)/2, simple = TRUE)[[1]]
}

optim(par=-1, fn = f1)

#$par
#[1] -2.440637
#
#$value
#[1] 1.140988e-07
#
#$counts
#function gradient 
#      56       NA 
#
#$convergence
#[1] 0
# 
#$message
#NULL

编辑:

考虑到 Nelder-Mead 对于一维优化不可靠的警告,优化 t 值的其他两种方法。警告只是意味着有/有更好的方法来优化单变量函数。

optim(par=-1, fn = f1, method="Brent", lower = -100, upper=100)
optimize(f1, interval = c(-100,100))

【讨论】:

  • 谢谢,但为什么我会收到以下警告:Warning message: In optim(par = -1, fn = f1) : one-dimensional optimization by Nelder-Mead is unreliable: use "Brent" or optimize() directly
  • f2 可让您检查原始函数中的参数。你可以无视它
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 2016-01-16
  • 2015-01-25
  • 2020-03-17
  • 1970-01-01
  • 2021-06-29
相关资源
最近更新 更多