[英]Find median in R (discrete random variables)
May I know how I can find the median of x from y in R?我可以知道如何在 R 中从 y 中找到 x 的中位数吗? y is the probability of x here.
y 是这里 x 的概率。 For instance, 0.3 is P(X=1) and 0.05 is P(X=2).
例如,0.3 是 P(X=1),0.05 是 P(X=2)。 The median that I have calculated by hand is 3. I have tried using median(y) but I can only get 0.25 which is the median of data set y.
我手工计算的中位数是 3。我尝试使用 median(y) 但我只能得到 0.25,这是数据集 y 的中位数。 Is there anyway that I can use to combine x and y to find the median of x?
无论如何,我可以用来组合 x 和 y 来找到 x 的中值吗?
x=1:5
y=c(0.3,0.05,0.25,0.25,0.15)
Here is how you subset a vector by index.这是按索引对向量进行子集化的方法。
x[y == median(y)]
# 3 4
As I understand about your x
and y
is P(X = x
) = y
, and define median as first value which has cdf >.5.据我了解,您的
x
和y
是 P(X = x
) = y
,并将中值定义为 cdf >.5 的第一个值。
You may try你可以试试
library(dplyr)
z <- cbind(x,y) %>%
as.data.frame() %>%
mutate(z = cumsum(y) > 0.5)
x[first(which(z$z))]
[1] 3
Perhaps:也许:
library(spatstat)
#> Loading required package: spatstat.data
#> Loading required package: spatstat.geom
#> spatstat.geom 2.3-0
#> Loading required package: spatstat.core
#> Loading required package: nlme
#> Loading required package: rpart
#> spatstat.core 2.3-1
#> Loading required package: spatstat.linnet
#> spatstat.linnet 2.3-0
#>
#> spatstat 2.2-0 (nickname: 'That's not important right now')
#> For an introduction to spatstat, type 'beginner'
x=1:5
y=c(0.3,0.05,0.25,0.25,0.15)
weighted.median(x, y)
#> [1] 2.6
Created on 2021-11-23 by the reprex package (v2.0.1)由代表 package (v2.0.1) 于 2021 年 11 月 23 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.