PROGRAMA DE DOCTORADO EN SALUD PÚBLICA Bioestadística PROGRAMA DE DOCTORADO EN SALUD PÚBLICA
Primera clase: Presentación del curso Stata Bases de datos de trabajo Definition of Epidemiology, its objectives and analytic procedures Prevalence, Incidence, Odds Mortality, Lethality, Proportionate Mortality, Cause-specific mortality Rates and ratios, odds-ratios, risk-ratios or relative-risks Reality, tests and gold standards: validity and reliability Sensitivity and specificity; positive and negative predictive value Concordance and the Kappa statistic Case series and cross-sectional studies; case-control and cohort studies Prospective and retrospective studies Clinical trials, what are they? Random and systematic error. Selection and information biases Confounding?
PRESENTACIÓN DEL CURSO
Objetivo general: Presentar los fundamentos del tratamiento de datos cuantitativos en el sector salud, tanto en la practica profesional y académica, así como en la ejecución de proyectos de investigación y desarrollo
Capacidades a desarrollar: Análisis exploratorio, estadística descriptiva y estimaciones de parámetros estadísticos Inferencias para datos en salud pública y epidemiología: prevalencias e incidencias, regresiones simples y múltiples, análisis de sobrevivencia, análisis longitudinal. Utilizar Stata proficientemente para realizar los análisis descritos previamente. Interpretar y transmitir correctamente resultados provenientes de estos análisis
Metodología: Cero fórmulas, 100% software Integración de teoría y práctica con ejemplos y datos de la realidad local Trabajo individual con datos reales 3 controles de lectura 4 ejercicios 1 trabajo final Prueba inicial/final
Contactos Mirko Zimic Jefe de la Unidad de Bioinformática y Biología Computacional, Facultad de Ciencias, UPCH 3190000 anexo 2604 mzimic@jhsph.edu mzimic@gmail.com http://www.upch.edu.pe/facien/dbmbqf/docentes.htm http://www.abeperu.net/
Porqué STATA?
Porqué usamos Stata? Opciones orientadas a BIOestadística Programa preferido en escuelas de medicina y salud pública en los EEUU y otros paises Precios accesibles: $72 y $100 por copia para licencias educativas y corporativas Pago único por uso perpetuo de todos sus módulos con actualizaciones gratuitas
Stata tiene, SPSS no… Manejo de incidencias, prevalencias, y razones de riesgo (regresiones para RR también) Regresión logística condicional para estudios de caso-control apareado Ajuste directo/indirecto de tasas/proporciones Cálculo de tamaño de muestra Meta-análisis
Amplio soporte en Perú: Licencias y cursos en San Marcos y UPCH Utilizado por diversos grupos (NMRCD, UPCH, PRISMA, INEI, OGE, PUCP, etc.) Asesoría de bioestadísticos locales (ABE) Base de usuarios rápidamente creciente
Resultados (.log) Historia de comandos Comandos (uno cada vez) (.do) Variables (.dta) Resultados (.log)
Semana 1. Introducción a los conceptos estadísticos - Definición de observables físicos. - Cuantificación y medición. - Procesos determinísticos y procesos aleatorios. - Constantes y variables aleatorias. - Tipos de variables. - Definición frecuentista de probabilidad - Distribuciones probabilísticas especiales - Distribuciones sesgadas. - Definición de parámetros y estimadores. - Definición de la Estadística Bayesiana.
What is Probability? Two Schools: * Frequentists * Bayesians
Frequentists definition of Probability …Probability of an event is the limit of the frequency at which it occurs when the number of trials tends to infinity…
Probability Probability is the numerical measure of the likelihood that the event will occur. Value is between 0 and 1. Sum of the probabilities of all mutually exclusive and collective exhaustive events is 1. 1 Certain .5 Impossible
Discrete Probability Distribution Example Event: Toss 2 Coins. Count # Tails. Probability distribution Values probability 0 1/4 = .25 1 2/4 = .50 2 1/4 = .25 T T T T
SAMPLES AND POPULATIONS: INFERENCE AND PROBABILITY PN Inference Probability Sample S1 S2 Sn 18
Sometimes the frequentists definition may not be applied… For example, under the question: What is the probability that China declares the war to the US and a world nuclear catastrophe occurs?
Bayesian definition of probability …Probability can be understood as the hope or expectancy (particular belief) that the event may occur… So the answer to the last question may be any number that represents a particular belief
The probabilistic concept produces a natural classification: Fixed Numbers (Constants) Random Variables (unfixed, may change with a certain probability distribution)
For example, some constants are: The speed of light in vacuum (300 000 Km/s) Avogadro’s number Boltzmann’s constant Planck’s constant
Some examples of random variables The number of bacteria that grow on a plaque The number of neurons on a human brain The time that takes a flight from Chicago to Baltimore Human adult blood pressure Cholesterol level The money your wife spends monthly !!
A random variable has a PROBABILITY DISTRIBUTION The probability distribution can be seen as a ‘frequency plot’ or as an ‘histogram’
What about your HEIGHT, is it a random variable ? (Suppose you are in the stationary phase of growth)
What do you need to do in order to KNOW your height? …Mmmmm, I need to MEASURE ! Remember !, MEASURING is a key concept, we will go over it later
Just to remind: To MEASURE is nothing else than to ‘assign’ a NUMBER to a certain characteristic of a physical observable, and for that we need to use a MEASUREMENT INSTRUMENT
Suppose you measure yourself several times during a week… Will you obtain always the same value?
A Clarification… A RANDOM VARIABLE has a probability distribution, BUT its realization (the value obtained once it’s measured) is then a CONSTANT (fixed value)
What causes randomness? How do we know if an observable is determined by a random variable or a constant? Remember that to ‘know’ something is equivalent to measure it several times and make predictions and inferences on it
Can the process of ‘measuring’ play any role in the ‘randomness’ of the observables?
During a measurement, the ‘instrument of measurement’ INTERACTS with the system and may PERTURBE it randomly, because the measuring conditions may not be ‘exactly’ repeated
Therefore, a deterministic world? Originally, Physics, Chemistry and Biology were born in a deterministic framework.
Classical Physics is deterministic According to Newton’s laws, we can ‘predict’ how a system is going to behave in the future
Classical Chemistry is deterministic A + B C
Classical Biology is deterministic A – T G – C
Consequences of a deterministic world… Suppose we are able to ‘calculate’ the dynamics of ‘every’ molecule in the brain, and predict a future state… Then we could predict what a particular person is going to think or even do !!!
What are the difficulties? The calculation is incommensurably complex, at the point that neither all the computers in the world working together at a billion times faster than they are could complete the calculations in an acceptable time (in less than several hundreds of years) At the end of the calculations, the individual is already dead
Is the computational power limitation the only obstacle?
Remember that in order to solve for the dynamics of any system, we need to ‘know’ the initial conditions How can we ‘know’ the initial conditions? Just ‘measuring them’… and after measuring, we inevitably introduce uncertainty
What about ‘giving’ the initial conditions instead of measuring them? Can we then use our computational capacity to ‘predict’ how the system is going to evolve?
For example: What’s going on when we roll a dice? Given the initial conditions we can calculate how the dice is going to move and thus determine which face is going to be up. The randomness of a ‘dice roll’ resides in the fact that the initial conditions during the throw are never the same for a human arm So, a finest and precise robot arm, that always ‘throw’ the dice in the SAME WAY could be designed such that ‘always’ get an ace.
What can we conclude about it? So, if a robot arm can always throw an ace, what happened to the randomness of the process? What can we conclude about it?
The randomness is due to the variability on the initial conditions Many systems are very sensible even to extremely small variations on the initial conditions: This is called Dynamical Instability or CHAOS
Chaos is not always as ‘bad’ as it sounds… Sometimes, it can really be beautiful. An example of this are the FRACTALS
Atan Method Fractals
Miscellaneous
Bubbles
3D Phoenix Spirals
Summarizing The ‘randomness’ of a random variable resides on: The variability of the initial conditions The dynamical instability The perturbation suffered during a measurement
Important Conclusion: Determinism and Random Behavior are not actually divorced, but they are connected through the Dynamical Equations. Therefore, Random Behavior is a consequence of determinism under special conditions
Tipos de variables
Clasificación general: Categórica Cuantitativa o numérica Nominal Ordinal Discreta Continua
Ejemplos: Nominales: Sexo, estado civil, presencia de morbilidad, resultado del tratamiento Ordinales: Severidad de morbilidad, riesgo quirúrgico, resistencia a antibioticos Discretas: Cociente intelectual, tiempo de tratamiento u hospitalización Contínuas: concentración de alcohol en la sangre
Las variables continuas El carácter continuo de una variable lo da la naturaleza intrínseca del observable físico y es independiente de la manera cómo se mida (i.e. del instrumento utilizado) ó de la manera cómo se reporte la medición
Efecto de la manera ‘cómo se mide’ una variable Imaginemos que medimos la induración del PPD en varios pacientes, y para ello utilizamos una regla milimetrada. Las dimensiones medidas para diferentes personas fueron: 5mm, 12mm, 9mm, 32mm, 21mm Aparentemente estamos frente a una variable discreta, aunque en realidad la induración (longitud) es y debe tratarse de manera continua.
Efecto de la manera ‘cómo se reporta’ una variable Imaginemos que medimos la duración de la permanencia en UCI de pacientes en un hospital. Los tiempos medidos para diferentes pacientes fueron: 15días, 2días, 9días, 12días, 31días Aparentemente estamos frente a una variable discreta, aunque en realidad el tiempo es y debe tratarse de manera continua.
En la base de datos: id_reg Región inf_sexo Sexo inf_edad Edad p35 ¿Cuál es el nivel de educación alcanzado? p56 En su grupo de amigos, ¿Con qué frecuencia fuma? p58 ¿Cuándo fue la primera vez que Ud. fumó cigarrillos? p59 ¿Qué edad tenía cuando fumó cigarrillos por primera vez? p62 Y, ¿Cuándo fue la última vez que Ud. fumó cigarrillos? p64 ¿Con qué frecuencia fuma Ud. cigarrillos? p65 Más o menos, ¿Cuántos cigarrillos al día fuma Ud.? p66 Más o menos, ¿Cuántos cigarrillos fumó en los últimos 30d? p87 ¿Cuándo fue la primera vez que Ud. bebió? p88 La primera vez que Ud. bebió, ¿Qué bebida tomó? p89 ¿A que edad Ud. bebió por primera vez? p90 ¿Con quién estaba Ud. la primera vez que tomó? p92 Y, ¿Cuándo fue la última vez que Ud. bebió? p94 ¿Con qué frecuencia toma Ud. alguna bebida alcohólica? arsoc2 Estrato social
En sus trabajos, que tipo de dato es su variable respuesta, resultado o desenlace principal?
Categorización/discretización: Las variables continuas pueden ser convertida en variables discretas y hasta en categóricas En este proceso se pierde información (precisión) La información debe obtenerse al mayor nivel de precisión posible y luego agruparse si fuera necesario (discretización)
Definiciones especiales: Categóricas dicotómicas o de más de dos valores Cuantitativas con distribución normal o no Discretas tipo conteo: números de casos reportados, CD4, carga viral o parasitaria Cuantitativas truncadas: ingresos, edad, peso/talla Tiempo para evento: edad de inicio del consumo (considerando a no consumidores)
DESCRIBIENDO VARIABLES DICOTOMICAS
Variables dicotómicas:
Pero, nos interesa realmente la muestra o la población? Esta exploración es parte de un proceso de inferencia estadística Queremos extrapolar conclusiones a la población Nuestro primer objetivo es hacer una estimación a nivel de la población: Cálculo numérico de un cierto parámetro en la población En forma puntual y con intervalo de variabilidad
Definición frecuentista de probabilidad
Distribuciones probabilísticas especiales
Dos bases de datos hipotéticas… Es importante tener una imagen visual de la distribución de la variable Datos de baja variabilidad La media provee una buena representación de los valores en la base de datos. Al incrementar datos la distribución cambia.. Datos con alta variabilidad La media ya NO provee ahora una buena información de los datos como sucedía anterioremente
Perfil de la distribución Describe cómo los Datos están Distribuídos Caracterización del perfil de la distribución: Simétrica o sesgada
Recordemos las características de una variable continua con distribución normal… Figure 10.10 6
Perfil de la distribución Describe cómo los Datos están Distribuídos Caracterización del perfil de la distribución: Simétrica o sesgada Simétrica Media = Mediana = Moda
Gráficos ‘tallo y hoja’ comando ‘stem’ de STATA
How does the standard deviation affect the shape of f(x)? How does the expected value affect the location of f(x)? m = 10 m = 11 m = 12 Bioestadística Aplicada
Fenómenos tipo Bernoulli: Se aplican a variables dicotómicas Representan la ocurrencia o no ocurrencia de UN evento, por ejemplo: el sexo de CADA UNA de las personas encuestadas Toman solamente dos posibles valores o estados: hombre (1) o mujer (2) Solo se aplican a nivel unitario: un dato, persona u observación
Distribución Binomial: Es un conjunto de variables Bernoulli del mismo tipo, por ejemplo, el sexo de las 4,850 personas encuestadas La variable en estudio (sexo) tiene también dos valores (hombre/mujer), los cuales ocurren con frecuencias relativas (p) y (1-p) simétricas El valor p es la frecuencia relativa o proporción de hombres entre las personas encuestadas
Rápidamente:
Transformando sexo a 0/1:
n=2 n=5 n=30 n=3 n=15 n=60
El Teorema del Límite Central da validez a los intervalos de confianza La media de una muestra “grande” de datos de cualquier tipo sigue una distribución normal Esto aún se cumple para datos binomiales (sexo, prevalencia, sensibilidad, etc) Qué es una muestra grande? Eso varía según cada tipo de dato (entre otras cosas) A medida que el tamaño de muestra crece, la distribución de la media muestral se hace más normal
AN ILLUSTRATION OF THE CENTRAL LIMIT THEOREM Bioestadística Aplicada 80
Comandos usados en STATA para identificar el tipo de variable: Codebook Inspect
ATENCION ! STATA puede identificar un tipo de variable de manera erronea ! Debemos apoyarnos en la ciencia, en nuestro conocimiento previo de la variable con que estamos trabajando.
Continuous Models on the Line Normal Logistic Cauchy Laplace Student Non-central Student Bioestadística Aplicada
Normal Distribution Mean= 0 SD = 0.5, 1, 2 Bioestadística Aplicada
Logistic distribution Mean=0 SD=0.5, 1 Bioestadística Aplicada
Student distribution Degrees of freedom= 1,10,100 Bioestadística Aplicada
Laplace distribution Mean=0 SD=0.5, 1, 5 Bioestadística Aplicada
Continuous Models on the Half Line Exponential Gama Chi-square Non central Chi-square F Non central F Weibull Bioestadística Aplicada
Exponential distribution Scale parameter = 0.5, 1, 2 Bioestadística Aplicada
Chi-square distribution Degrees of freedom = 3, 5, 10,15 Bioestadística Aplicada
F distribution Degrees of freedom = (3,3), (10,10), (30,30) Bioestadística Aplicada
Continuous Models on a Finite Interval Beta Uniform Bioestadística Aplicada
Uniform distribution P = 1/3 Bioestadística Aplicada
Beta distribution Parameters: (2,15), (5,15), (15,5) Bioestadística Aplicada
Discrete Models Binomial Poisson Negative Binomal Uniform Bioestadística Aplicada
Binomial distribution P= 0.2, 0.5, 0.8 Bioestadística Aplicada
Poisson distribution Intensity parameter = 1, 3, 7 Bioestadística Aplicada
Negative Binomial P N 0.5 10 0.4 3 0.4 6 Bioestadística Aplicada
Distribuciones sesgadas
Perfil de la distribución (skewness coefficient) Describe cómo los Datos están Distribuídos Caracterización del perfil de la distribución: Simétrica o sesgada
Perfil de la distribución Describe cómo los Datos están Distribuídos Caracterización del perfil de la distribución: Simétrica o sesgada Sesgada izquierda Simétrica Mean Median Mode Mean = Median = Mode
Perfil de la distribución Describe cómo los Datos están Distribuídos Caracterización del perfil de la distribución: Simétrica o sesgada Sesgada izquierda Simétrica Sesgada derecha Media Mediana Moda Media = Mediana = Moda Moda Mediana Media
Análisis de OUTLIERS: Datos sesgados: Valores que se exceden de 3 rangos intercuartiles por debajo del primer cuartil Q1 o por encima del tercer cuartil (Q3) (percentiles 25 y 75 respectivamente) Sesgada izquierda Sesgada Positiva outlier region outlier region Q1 Q3 Q1 Q3 Q1 – 3(Q3 – Q1) Q3 + 3(Q3 – Q1)