简体   繁体   中英

Find median in R (discrete random variables)

May I know how I can find the median of x from y in R? y is the probability of x here. For instance, 0.3 is P(X=1) and 0.05 is 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. Is there anyway that I can use to combine x and y to find the median of 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM