'How to calculate PMF of sample median for discrete random variable in R?
A bag contains 5 billiard balls numbered 1, 2, 3, 4, 5. A random sample of size n = 3 is drawn without replacement from the bag. What is the probability mass function of the sample median?
Here is what I have:
library(listviewer) sampleSpaceAndMedian = list()
# the random samples (1,2,3), (1,3,2), (2,1,3),
# (2,3,1), (3,1,2), and (3,2,1) have the same mean
# therefore, belong to the same equivalence class
for (a in 1:3){
for (b in 2:4){
for (c in 3:5){
# a unique random sample of size 3 (ignores the order)
if (b > a && c > b){
tString = paste(toString(a), toString(b), toString(c), toString(median(c(a,b,c))), sep = " ")
sampleSpaceAndMedian <- append(sampleSpaceAndMedian, tString)
}
}
}
}
# the random sample is in the first three columns
# median is the fourth column
jsonedit( sampleSpaceAndMedian )
```
Can you please help me to get the PMF? Thanks.
Solution 1:[1]
You can use combn to get all the combinations of a vector and apply a function to it:
combn(1:5, 3)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,] 1 1 1 1 1 1 2 2 2 3
#[2,] 2 2 2 3 3 4 3 3 4 4
#[3,] 3 4 5 4 5 5 4 5 5 5
To get the distribution of the median you can use the following:
prop.table(table(combn(1:5, 3, median)))
#> 2 3 4
#>0.3 0.4 0.3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stefano Barbi |
