Home > Enterprise >  Find median in R (discrete random variables)
Find median in R (discrete random variables)

Time:11-23

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)

CodePudding user response:

Here is how you subset a vector by index.

x[y == median(y)]
# 3 4

CodePudding user response:

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

CodePudding user response:

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)

  • Related