在下面我的R代码的最后一行中,我使用optimize()
查找使df2
函数最小化的ncp_diff
。
但是,我想知道是否可以uniroot()
代替optimize()
来实现这种最小化?
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))
}
ncp_diff <- function(df2, target = 0.15){
the_ncp <- ncp(df2)
return(abs(abs(the_ncp[2] - the_ncp[1]) - target))
}
optimize(ncp_diff, c(0, 1000)) ## HERE can I use `uniroot()` instead of `optimize()`
答案 0 :(得分:1)
<ng-container matColumnDef="startdate">
<mat-header-cell *matHeaderCellDef mat-sort-header><b>Start Date</b> </mat-header-cell>
<mat-cell *matCellDef="let item"> {{item.itemCategoryRows.startdate | date: 'dd/MM/yyyy'}} </mat-cell>
</ng-container>
<ng-container matColumnDef="enddate">
<mat-header-cell *matHeaderCellDef mat-sort-header><b>End Date </b> </mat-header-cell>
<mat-cell *matCellDef="let item"> {{item.itemCategoryRows.enddate | date:'mediumDate'}} </mat-cell>
</ng-container>
编辑:
为了使用相同的间隔(0,1000),我们可以寻找一种方法来解决以下情况:下限值和上限值都在数字线的同一侧产生结果。由于这是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))
}
ncp_diff <- function(df2, target = 0.15){
the_ncp <- ncp(df2)
return((the_ncp[2] - the_ncp[1]) - target)
}
uniroot(ncp_diff, c(100, 1000)) #
$root
[1] 336.3956
$f.root
[1] 3.74663e-09
$iter
[1] 7
$init.it
[1] NA
$estim.prec
[1] 6.103516e-05
tryCatch