r - 给定R中的条件,如何向后求解未知数?
问题描述
对于一组输入(见下文),当我运行以下 R 代码时,我得到两个存储在ncp
. 但是我想知道(即)中df2
这两个答案之间的区别应该是什么?ncp
abs(ncp[2] - ncp[1])
.15
那么,其他一切都修复了,应该df2
是什么abs(ncp[2] - ncp[1]) = .15
?这可以在R中完成吗?
alpha = c(.025, .975); df1 = 3; peta = .3 # The input
f <- function(alpha, q, df1, df2, ncp){ # Notice `ncp` is the unknown
alpha - suppressWarnings(pf(q = (peta / df1) / ((1 - peta)/df2), df1, df2, ncp, lower = FALSE))
}
ncp <- function(df2){ # Root finding: finds 2 `ncp` for a given `df2`
b <- sapply(c(alpha[1], alpha[2]),
function(x) uniroot(f, c(0, 1e7), alpha = x, q = peta, df1 = df1, df2 = df2)[[1]])
b / (b + (df2 + 4))
}
# Example of use:
ncp(df2 = 108) # Answers: 0.1498627 0.4100823
# What should `df2` be so that the difference between 2 answers is `.15`
解决方案
包中的optim
andoptimize
函数stats
是处理此类问题的好方法。 optimize
更简单,处理单变量情况。这是一个示例解决方案:
# Define a function that we want to minimise the output of
ncp_diff <- function(df2, target = 0.15){
the_ncp <- ncp(df2)
return(abs(abs(the_ncp[2] - the_ncp[1]) - target))
}
# try it out - how far out is df2 = 108 from our target value?
ncp_diff(108) # 0.1102
# find the value of ncp_diff's argument that minimises its return:
optimize(ncp_diff, interval = c(0, 1000)) # minimum = 336.3956
ncp(336.3956) # 0.218, 0.368
请注意,虽然 336.3956 是一个解决方案,但它不一定是解决方案。您需要注意局部最小值。不过,处理这个问题超出了简单答案的范围。
推荐阅读
- html - 带有按钮的图像如何保持原位(响应性)?
- javascript - 上传文件到其他服务时如何获取上传进度?
- reactjs - 在初始安装时反应 useEffect 防止
- reactjs - 在聊天项目中动态更新 React 组件的问题
- r - 在 Windows 上检测中文字符时出现 str_detect() 错误
- javascript - 通过事件监听器将事件和元素传递给处理程序
- zapier - 尝试使用 Integromat 进行 Podio API 调用,返回 403 禁止 - InvalidAccessTokenError
- spring-webflux - 在生产者 Spring Reactive Kafka 中使用多个主题配置
- asp.net - 在特定实体上使用身份框架
- android - 创建启动系统应用程序“文件”的意图