r - 如何计算 h 点(在 R 中)
问题描述
我正在尝试编写一个函数来计算 h 点。该函数是在秩频率数据帧上定义的。考虑以下几点data.frame
:
DATA <-data.frame(frequency=c(64,58,54,32,29,29,25,17,17,15,12,12,10), rank=c(seq(1, 13)))
h点的公式是:
if {有一个 r = f(r), h-point = r } else { h-point = f(i)jf(j)i / j-i+f(i)-f(j) } 其中 f (i) 和 f(j) 是第 i 个和第 j 个秩的对应频率,i 和 j 是 i<f(i) 和 j>f(j) 的相邻秩。
这是我到目前为止所做的:
h_point <- function(data){
x <- seq(nrow(data))
f_x <- data[["frequency"]][x]
h <- which(x == f_x)
if(length(h)>1) h
else{
i <- which(x < f_x)
j <- which(x > f_x)
s <- which(outer(i,j,"-") == -1, TRUE)
i <- i[s[,1]]
j <- j[s[,2]]
cat("i: ",i, "j: ", j,"\n")
f_x[i]*j - f_x[j]*i / (i-j + f_x[i]-f_x[j])
}
}
在 中DATA
,h 点是——12
因为 x = f_x。然而,
h_point(DATA)
i: j:
numeric(0)
我在这里做错了什么?
解决方案
我看过你之前的帖子如何计算 h 点,但必须说我不太遵循你计算 h 点的方法。
基于我发现的h点的定义
我认为更简单的方法是使用approxfun
创建函数频率(等级),然后使用uniroot
找到 h 点:
get_h_point <- function(DATA) {
fn_interp <- approxfun(DATA$rank, DATA$frequency)
fn_root <- function(x) fn_interp(x) - x
uniroot(fn_root, range(DATA$rank))$root
}
get_h_point(DATA)
#[1] 12
推荐阅读
- android - 如何禁用材质滑块小部件
- python - 模型数据的空间变化垂直坐标 - 编写 netCDF 文件 (xarray)
- compilation - Clang 编译所有源文件,即使它们没有被更改
- asp.net-mvc - 在 Visual Studio 代码上支持 .NET Framework 4.x
- android - Webrtc - 未收到任何音频
- spring - 一次只有一个用户使用整个 Web 应用程序 - Spring Boot
- c++ - Define field with macro, but Field cannot have type 'void' and/or Expected ')'
- laravel - 在 Laravel Blade 文件中使用 Input 类
- hibernate - hibernate envers mapkeyenumerated
- ansible - Ansible:从变量名引用变量内容