R 查找范围值,其中X为中点
我有一组从0到1的数字。给定集合中的一个值X,我想找到范围值(高和低),其中集合中Y%的值在高和低之间,其中X是中点 假设这些数字是均匀分布的。假设X=0.4,Y=20%,我需要一个函数,该函数将给出: 高=0.5 低=0.3R 查找范围值,其中X为中点,r,R,我有一组从0到1的数字。给定集合中的一个值X,我想找到范围值(高和低),其中集合中Y%的值在高和低之间,其中X是中点 假设这些数字是均匀分布的。假设X=0.4,Y=20%,我需要一个函数,该函数将给出: 高=0.5 低=0.3 如何在R中做到这一点?更新:根据评论中的额外信息,这将满足OP的要求: foobar <- function(x, mid, y) { ## x, input data on range 0,1 ## mid, midpoint X in OP's
如何在R中做到这一点?更新:根据评论中的额外信息,这将满足OP的要求:
foobar <- function(x, mid, y) {
## x, input data on range 0,1
## mid, midpoint X in OP's Q
## y, % of points around mid
sx <- sort(x)
want <- sx >= mid
## what do you want to do if y% of x is not integer?
num <- floor(((y/100) * length(x)) / 2)
high <- if((len <- length(want[want])) == 0) {
1
} else {
if(len < num) {
tail(sx, 1)
} else {
sx[want][num]
}
}
low <- if((len <- length(want[!want])) == 0) {
0
} else {
if(len < num) {
head(sx, 1)
} else {
rev(sx[!want])[num]
}
}
res <- c(low, high)
names(res) <- c("low","high")
res
}
我们可以扩展该函数以允许默认值为0、1的任意范围:
bar <- function(x, y, min = 0, max = 1) {
## x is the mid-point
## y is the % range about x, i.e. y/2 either side of x
## min, max, the lower and upper bounds on the data
stopifnot(x >= min & x <= max)
x + (c(-1,1) * (((y/100) / 2) * (max - min)))
}
> bar(0.4, 20)
[1] 0.3 0.5
> bar(0.6, 20, 0.5, 1)
[1] 0.55 0.65
> bar(0.4, 20, 0.5, 1)
Error: x >= min & x <= max is not TRUE
bar=min&x bar(0.4,20)
[1] 0.3 0.5
>巴(0.6,20,0.5,1)
[1] 0.55 0.65
>巴(0.4,20,0.5,1)
错误:x>=min&x这是一个相当简单的表单
interval <- function(data, centre, qrange, type=1) { #type as in ?quantile
qcentre <- ( length(data[data<centre]) + #quantile of centre
length(data[data == centre])/2 ) / length(data)
quantile(data, c( max(0, qcentre-qrange/2), qcentre,
min(1, qcentre+qrange/2) ), type=type )
}
可以处理极值和非均匀分布的说明;请注意,sqrt(0.95)=0.974679…
:
> set.seed(123)
> interval(data=runif(100000)^2, centre=0.95, qrange=0.2)
87.456% 97.456% 100%
0.7634248 0.9499948 0.9999846
还有一幅插图再现了加文·辛普森的例子:
> set.seed(1)
> interval(data=runif(20), centre=0.4, qrange=0.2)
30% 40% 50%
0.3800352 0.3841037 0.5728534
我只是用均匀分布的假设来让例子更清楚。我需要在不一定均匀分布的集合上使用该函数。@Dave啊,这是一个重要的说明-你的意思是想计算哪些值在X的+/-Y/2%范围内,然后给出限制?我认为用分位数应该很容易做到。给我一分钟…@Dave我想我现在有了-看看我最新的答案。有几个(3)实现细节需要澄清,因为我猜测了一些合理的东西,但这可能不是您想要的。请看我的更新末尾的Q。@Gavin哇-回答得很好!我想我希望mid两边最多有y/2%。因此,如果mid=max,那么正好在mid下方的high=max和low=y/2%。y永远不会是整数。@Dave好的,这就回答了我的问题2。我的Q3呢?中!=最大值,但没有大于中间值的y/2
%观测值?在这种情况下,您是否仍希望它返回max(即1)?目前,我返回的最大值高于中点。容易修复,只需要知道你想要什么?那我的Q1呢?
> set.seed(42)
> interval(data=runif(1000000), centre=0.4, qrange=0.2)
29.9793% 39.9793% 49.9793%
0.3003162 0.3999986 0.5001484
> set.seed(123)
> interval(data=runif(100000)^2, centre=0.95, qrange=0.2)
87.456% 97.456% 100%
0.7634248 0.9499948 0.9999846
> set.seed(1)
> interval(data=runif(20), centre=0.4, qrange=0.2)
30% 40% 50%
0.3800352 0.3841037 0.5728534