In [66]:
using StatsBase, DataFrames, Plots, Distributions, Combinatorics, PrettyTables, FreqTables, Crayons
gr()
Plots.GRBackend()
In [67]:
using Dates
Dates.format(now(), "E, dd U yyyy HH:MM:SS")
"Friday, 09 May 2025 06:51:41"

Distribuciones Muestrales¶

Las medidas que se calculan sobre una población se llaman parámetros y las que se calculan sobre una muestra se llaman Estadísticos o Estadígrafos. Para los parámetros usamos letras griegas y para los estadísticos letras latinas.

Población Muestra
media $\mu$ $\bar{X}$
varianza $\sigma^2$ $S^2$
desviación estándar $\sigma$ $S$
proporción $\pi$ $p$
tamaño $N$ $n$

Parámetros: son las características de la población, son generalmente desconocidos

Estadísticos o Estadígrafos: son funciones de los valores muestral

En la práctica se saca una muestra representativa de la población para hacer inferencia estadística.

La muestra debe ser obtenida al azar o aleatoriamente, significa, que todo elemento de la población tiene la misma probabilidad de ser elegido.

Inferencia: sacar conclusiones para toda la población a partir de una muestra.

Ejercicio¶

Sea la población: 1,2,3,4,5,6 y obtengamos todas las muestras de tamaño 3 sin orden y sin reemplazo.

Cálculo de los parámetros¶

In [68]:
Pob = [1,2,3,4,5,6] 
μ = mean(Pob)
3.5
In [69]:
σ² = var(Pob, corrected=false)
2.9166666666666665
In [70]:
σ = std(Pob, corrected=false)
1.707825127659933
In [71]:
N = length(Pob)
6

Para la proporción interesa los pares

In [72]:
conteo_pares = count(iseven, Pob)
3
In [73]:
π = conteo_pares/N
0.5

Muestras¶

Obtengamos las muestras de tamaño 3. Salen $\binom{5}{3}=20$.

In [74]:
n = 3
muestras = collect(combinations(Pob, n)) 
nmu= binomial(N,n)
20
In [75]:
medias_m = round.(mean.(muestras),digits=5)
20-element Vector{Float64}:
 2.0
 2.33333
 2.66667
 3.0
 2.66667
 3.0
 3.33333
 3.33333
 3.66667
 4.0
 3.0
 3.33333
 3.66667
 3.66667
 4.0
 4.33333
 4.0
 4.33333
 4.66667
 5.0
In [76]:
varianzas_m = round.(var.(muestras, corrected=true),digits=5)
20-element Vector{Float64}:
 1.0
 2.33333
 4.33333
 7.0
 2.33333
 4.0
 6.33333
 4.33333
 6.33333
 7.0
 1.0
 2.33333
 4.33333
 2.33333
 4.0
 4.33333
 1.0
 2.33333
 2.33333
 1.0
In [77]:
prop_m = round.(count.(iseven, muestras)./n,digits=5)
20-element Vector{Float64}:
 0.33333
 0.66667
 0.33333
 0.66667
 0.33333
 0.0
 0.33333
 0.33333
 0.66667
 0.33333
 0.66667
 0.33333
 0.66667
 0.66667
 1.0
 0.66667
 0.33333
 0.66667
 0.33333
 0.66667
In [78]:
dfm = DataFrame(muestras=muestras, medias_m=medias_m, varianzas_m=varianzas_m, prop_m=prop_m)
pretty_table(dfm,header_crayon=crayon"red bold")
┌───────────────┬──────────┬─────────────┬─────────┐
│      muestras │ medias_m │ varianzas_m │  prop_m │
│ Vector{Int64} │  Float64 │     Float64 │ Float64 │
├───────────────┼──────────┼─────────────┼─────────┤
│     [1, 2, 3] │      2.0 │         1.0 │ 0.33333 │
│     [1, 2, 4] │  2.33333 │     2.33333 │ 0.66667 │
│     [1, 2, 5] │  2.66667 │     4.33333 │ 0.33333 │
│     [1, 2, 6] │      3.0 │         7.0 │ 0.66667 │
│     [1, 3, 4] │  2.66667 │     2.33333 │ 0.33333 │
│     [1, 3, 5] │      3.0 │         4.0 │     0.0 │
│     [1, 3, 6] │  3.33333 │     6.33333 │ 0.33333 │
│     [1, 4, 5] │  3.33333 │     4.33333 │ 0.33333 │
│     [1, 4, 6] │  3.66667 │     6.33333 │ 0.66667 │
│     [1, 5, 6] │      4.0 │         7.0 │ 0.33333 │
│     [2, 3, 4] │      3.0 │         1.0 │ 0.66667 │
│     [2, 3, 5] │  3.33333 │     2.33333 │ 0.33333 │
│     [2, 3, 6] │  3.66667 │     4.33333 │ 0.66667 │
│     [2, 4, 5] │  3.66667 │     2.33333 │ 0.66667 │
│     [2, 4, 6] │      4.0 │         4.0 │     1.0 │
│     [2, 5, 6] │  4.33333 │     4.33333 │ 0.66667 │
│     [3, 4, 5] │      4.0 │         1.0 │ 0.33333 │
│     [3, 4, 6] │  4.33333 │     2.33333 │ 0.66667 │
│     [3, 5, 6] │  4.66667 │     2.33333 │ 0.33333 │
│     [4, 5, 6] │      5.0 │         1.0 │ 0.66667 │
└───────────────┴──────────┴─────────────┴─────────┘

Las medias de las tres últimas columnas son:

In [79]:
mt = mean.(eachcol(select(dfm,2:4)))
3-element Vector{Float64}:
 3.5
 3.499998
 0.5
In [80]:
μₓ̄ = mt[1]
3.5
In [81]:
μₛ² = mt[2]
3.499998
In [82]:
μₚ = mt[3]
0.5

Las varianzas de las tres útimas columnas son:

In [83]:
vt = round.(var.(eachcol(select(dfm,2:4)), corrected=false),digits=5)
3-element Vector{Float64}:
 0.58333
 3.85
 0.05
In [84]:
σ²ₓ̄ = vt[1]
0.58333
In [85]:
σ²ₛ² = vt[2]
3.85
In [86]:
σ²ₚ = vt[3]
0.05

Distribución de frecuencias de las medias muestrales:

In [87]:
dft = select(dfm, Not(:muestras))
tm=freqtable(dft, :medias_m)
m = unique(medias_m)
data = hcat(m,tm)
header = ["Medias muestrales", "Frecuencia"]
pretty_table(data,header=header,header_crayon=crayon"yellow bold",alignment=[:c,:c])
┌───────────────────┬────────────┐
│ Medias muestrales │ Frecuencia │
├───────────────────┼────────────┤
│        2.0        │    1.0     │
│      2.33333      │    1.0     │
│      2.66667      │    2.0     │
│        3.0        │    3.0     │
│      3.33333      │    3.0     │
│      3.66667      │    3.0     │
│        4.0        │    3.0     │
│      4.33333      │    2.0     │
│      4.66667      │    1.0     │
│        5.0        │    1.0     │
└───────────────────┴────────────┘

Distribución de frecuencias de las varianzas muestrales:

In [88]:
tv=freqtable(dft, :varianzas_m)
v=unique(varianzas_m)
data1=hcat(v,tv)
header = ["Varianzas muestrales", "Frecuencia"]
pretty_table(data1,header=header,header_crayon=crayon"blue bold",alignment=[:c,:c])
┌──────────────────────┬────────────┐
│ Varianzas muestrales │ Frecuencia │
├──────────────────────┼────────────┤
│         1.0          │    4.0     │
│       2.33333        │    6.0     │
│       4.33333        │    2.0     │
│         7.0          │    4.0     │
│         4.0          │    2.0     │
│       6.33333        │    2.0     │
└──────────────────────┴────────────┘

Distribución de frecuencias de las proporciones muestrales:

In [89]:
tp=freqtable(dft, :prop_m)
p=unique(prop_m)
data2=hcat(p,tp)
header = ["Proporciones muestrales", "Frecuencia"]
pretty_table(data2,header=header,header_crayon=crayon"red bold",alignment=[:c,:c])
┌─────────────────────────┬────────────┐
│ Proporciones muestrales │ Frecuencia │
├─────────────────────────┼────────────┤
│         0.33333         │    1.0     │
│         0.66667         │    9.0     │
│           0.0           │    9.0     │
│           1.0           │    1.0     │
└─────────────────────────┴────────────┘
In [90]:
p1 = plot(m, tm./nmu, st=:sticks, lw=3, ylabel="Probabilidad", xguidefontsize=8)
p11 = plot!(Normal(mean(Pob),std(Pob, corrected=false)/sqrt(n)), lw=4, color=:black, label="Normal",fillalpha=0.3)
In [91]:
p2 = plot(v, tv./nmu, st=:sticks, lw=3, color=:red)
p21 = plot!(Chisq(n-1),0,15, lw=4, color=:black, label="Chi cuadrado",fillalpha=0.3)
In [92]:
p3 = plot(p, tp./nmu, st=:sticks, lw=3, color=:green)
p31 = plot!(Normal(π,sqrt(π*(1-π)/n)*sqrt((N-n)/(N-1))),lw=5)
In [93]:
p=[p1,p11]
q=[p2,p21]
r=[p3,p31]
plot(p1,p2,p3, layout=(3,1), titlefontsize=8,legend=false, title=["Medias muestrales" "Varianzas muestrales" "Proporciones muestrales"])

Un caso más grande¶

Con una población de tamaño $N=60$ y sacando muestras de tamaño $n=4$, se obtienen 487 635 muestras.

In [94]:
nm= binomial(60,4)
487635
In [95]:
using Distributions, StatsPlots
pobla = randn(60) .*20 .+ 50 # población
tammu=4   #  tamaño de muestra
muestras1 = combinations(pobla, tammu);
@time medias_mu = mean.(muestras1);
  0.044602 seconds (1.46 M allocations: 66.967 MiB, 42.81% gc time)
In [96]:
histogram(medias_mu, norm=true, bins=50, label="Medias muestrales", color=:green)
plot!(Normal(mean(pobla),std(pobla, corrected=false)/sqrt(tammu)), lw=4, color=:black, label="Normal",fillalpha=0.3)
In [97]:
@time varianzas_mu = var.(muestras1);
  0.052047 seconds (1.46 M allocations: 66.967 MiB, 47.64% gc time)
In [98]:
histogram((tammu-1)*varianzas_mu/var(pobla,corrected=false), norm=true, bins=50, label="Varianzas muestrales", color=:yellow)
plot!(Chisq(tammu-1),0,15, lw=4, color=:black, label="Chi cuadrado",fillalpha=0.3)
In [99]:
mprop = collect(muestras1)
props = [sum(mprop[i].<40)/tammu for i in 1:(nm)]
histogram(props,bins=6,normalize=true, leg=false)
plot!(Normal(mean(props),std(props,corrected=false)),lw=5)
In [100]:
printstyled("Hello\n"; color = :blue)
Hello