Inferencia estadística con - UAB...
Transcript of Inferencia estadística con - UAB...
Antonio Barbadilla
Group Leader Bioinformatics of Genome Diversity
Group Genomics, Bioinformatics & Evolution
Institut Biotecnologia I Biomedicina
Departament de Genètica i Microbiologia
UAB
Inferencia estadística con
http://bioinformatica.uab.cat/Inf_Est
La Web (plataforma web 2.0) del curso
Acerca de este curso
Visión integrada del análisis estadístico •El diseño experimental de partida •El tratamiento correcto de los datos primarios •Interpretación de la significación de la prueba estadística (Leek, J.T. & Peng, R.D. 2015. Statistics: P values are just the tip of the iceberg. Nature 520, 612, artículo).
•Curso previo (bio)estadística •Recordar y relacionar rápidamente todos los conceptos básicos •Ejemplos de datos e hipótesis que permiten captar análisis a efectuar •Uso de R
Acerca de este curso
Observed data point Observed data point Observed data point
0
Recordar y relacionar rápidamente todos los
conceptos básicos 0
2)(2
1
2
1)(
x
exfó H0:
HA:
Elements of a statistical test
•Null hypothesis: H0
•Alternative hypothesis: H1
•Region of rejection / Critical region
•p-value: the value p of the statistic used to test the null hypothesis
•α: level of significance
Tabla de decisión
The R Project for Statistical Computing http://www.r-project.org/
Tippmann, S. Programming tools: Adventures with R. Nature 517, 109-10 (2015)
An R starter kit ● Install R at the Comprehensive R Archive Network. This also provides an introduction to the system. ● Many researchers recommend using a (free) powerful interface called RStudio. ● Online tutorials: DataCamp, rOpenSci, Software Carpentry and R-bloggers.
R is an integrated suite of software facilities for data manipulation, calculation and graphical display Object oriented: Data object and Function object
R command line interface (CLI)
R GUI
Ventajas R: un todo en uno, paquete estadístico y más (6000 paquetes), lenguaje de programación, manejo base de datos, gran capacidad gráficos, gran capacidad simulación.
Vamos a simular y “demostrar” mediante simulación: Ley de los grandes números, Teorema central del límite, test de remuestreo (bootstrap),…
http://www.r-tutor.com/elementary-statistics
Elementary Statistics with R Chi Yau
•Poner orden a vuestros conceptos/nociones estadísticos. No 100 tests ni 250 fórmulas. •Invitación al pensamiento estadístico. Toda persona educada hoy debe conocer el razonamiento estadístico. •Saber plantear cuestiones medulares en la investigación de análisis de datos: ¿De dónde vienen los datos? ¿Tienen sentido los resultados? ¿Cuán fiables son tus inferencias o conclusiones?
Propuesta docente: Qué no es – Qué sí es este curso
Acerca de este curso
Sir Karl Popper (1902-1994)
An hypothesis (or theory) is scientific if it is liable to be rejected, if it can be denied by the facts. One hypothesis that is true regardless of the empirical evidence is “untestable" and therefore is not a scientific hypothesis
•¿Pulpo Paul adivina partidos mundial sudáfrica? •¿Horóscopo influye en nuestras vidas? •¿Las vacunas no inmunizan? •Tratamiento SIDA
Pensamiento crítico, riguroso
Los crédulos
De la vacuna de la difteria Teresa Forcades ha dicho que “está probada y funciona, pero no al cien por cien”. Léase artículo http://blogs.elpais.com/cosas-que-importan/2015/06/teresa-forcades-y-las-vacunas-.html
En 2001 el presidente sudafricano T. Mbeki puso en duda las medidas aceptadas para evitar la proliferación del SIDA después de leer durante una noche de navegación por la Web una página que negaba la relación del SIDA con el virus de la inmunodeficiencia adquirida.
Statistical reasoning is not spontaneous, it is not intuitive
•Hemisferio lógico (izquierdo, busca pautas) •Hemisferio derecho (intuitivo)
Pensamiento crítico, riguroso
Ejemplo 1. Journal of Neuroscience 20:RC64 (2000). Rojo : verde -> 2:1 (azar, no pauta) Ratón mejores resultados que humanos RRVRRRVRRVRVRVRV Ejemplo 2. The Monty Hall paradox - El problema de los dos condenados de tres enjuiciados Ejemplo 3. ¿Es más probable que el presidente incremente la ayuda estatal en educación o que incremente la ayuda estatal en educación mientras recorta subsidios autonómicos? ¿Abandona escenario crimen o abandona el escenario crimen por miedo a ser acusado?
Pensamiento crítico, riguroso
•Es una actitud ética por la búsqueda del conocimiento objetivo •Es una actitud en busca de la excelencia en el razonamiento, del rigor de pensamiento •Requiere un razonamiento educado y disciplinado
Statistical reasoning is not spontaneous, it is not intuitive
Optimal experiment design: one that allows acquire a desired amount of information at minimal cost
Statistics is the technology of the scientific method, and deals with:
1. The design of experiments and research, and
2. The statistical inference
Scientific method Set of principles and procedures for objectively prove or reject explanatory or predictive hypothesis of natural phenomena
2)(2
1
2
1)(
x
exf
Statistics is the bridge between the theoretical world (model) and the
empirical world (data)
x
•Statistic is science of data •El arte de los datos
DATA
Dato: Número con contexto 3,5, no dice nada pero 3,5 kg de mi hijo al nacer sí Lo datos deben reflejar una propiedad que se quiere describir o explicar
PROBABILISTIC MODEL
2)(2
1
2
1)(
x
exf
Variables aleatoria y modelos probabilísticos
Experimental Design
Information content of results of the experiment (empirical
data)
Statistical Inference Statistical hypothesis testing
Statistical Inference
El arte de decir, con la mayor coherencia posible, cosas de poblaciones a través del uso
óptimo de la información limitada que se tiene de ellas
Statistical Inference
1. Elección familia modelos probabilístico
2. Elección modelo concreto dentro de la familia
•Any quantitative statement or hypothesis about data must be supported by a statistical test
•If you say the mean treatment is larger that control you mean
STATISTICALLY SIGNIFICANT
p < 0.001 >
The Drosophila melanogaster Genetic Reference Panel: A Community Resource for Analysis of Population Genomics and Quantitative Traits. Nature 482: 173-178.
Sir Ronald Fisher (1890-1962)
Ronald A Fisher is the most influential scientist ever
•P-values - 3 million citations •Analysis of variance (ANOVA) - 1.57 million citations •Maximum likelihood estimation - 1.54 million citations •Fisher’s linear discriminant 62,400 citations •Randomization/permutation tests 37,940 citations •Genetic linkage analysis 298,000 citations •Fisher information 57,000 citations •Fisher’s exact test 237,000 citations
Sir Ronald Fisher (1890-1962)
The additive linear model
Stochastic model of an observation
Error or deviation or variation
The additive linear model
Stochastic model of an observation (variable response)
Error or deviation or variation
Sources of variation
Explanatory Variables (scientific target)
Reduction or control (statistical target)
•Internal
•External
•Measurement (systematic or random)
•Sampling
Sources of variation
Explanatory Variables (scientific target)
Reduction or control (statistical target)
•Internal
•External
•Measurement (systematic or random)
•Sampling
EXPERIMENTAL DESIGN
Leek, J.T. & Peng, R.D. (2015) Statistics: P values are just the tip of the iceberg. Nature 2015 520:612
THE DATA PIPELINE
Elementos del Diseño Experimental
•Objetivo
•Variables a medir
•Control variables ocultas
•Aleatorización
•Tamaño muestral
•Precisión o cantidad de información I = n/varianza
•Statistic is science of data •Statistic is the art of data
DATA
Dato: Número con contexto Tipos datos:
•Cualitativos (color, sexo, variante genética) •Cuantitativos
•Discretos (número de quetas o facetas en Drosophila melanogaster, número de vértebras en serpientes, bandas en caracoles) •Continuos (altura, peso, temperamento, C.I., tasa metabólica, producción lechera)
•Obtención de los datos
•Población
•Individuo
•Muestra
•Variable: numérica – cualitativa (% o proporción)
•Intercambio numérica <– >cualitativa
•Datos tabulados ID SNP1 SNP2 SNP3 SNP4 SNP5 STATUS SEX AGE BMI
1 C/C T/T C/C C/C G/G 0-Control Female 74 [25.9,29.0)
2 C/G C/C A/A C/G G/G 0-Control Male 50 [16.0,23.6)
3 C/G T/C C/C C/C G/T 0-Control Female 64 [16.0,23.6)
4 C/C T/T C/C C/C G/G 1-Case Male 67 [16.0,23.6)
5 C/C T/T C/C C/C G/G 0-Control Female 80 [29.0,52.2]
6 C/C T/T C/C C/C G/G 0-Control Male 79 [29.0,52.2]
7 C/G T/C C/A C/G G/G 1-Case Male 83 [16.0,23.6)
Source: http://bioinfo.iconcologia.net/snpstats/sampledata/sample1.txt
•Tipo estudio:
•observacional
•obtención muestra
•censo (muestreo que trata de incluir toda la población),
•experimento (respuesta tratamiento)
# Basic data types #Numeric > x <- 120.5 # assign a decimal value > x # print the value of x #Integer > N = as.integer(6) > N # print the value of N > N = as.integer(6.8978) # coerce a numeric value > N # print the value of N #Character > nombre = "Marcos" > nombre > x = as.character(3.14) > x # print the character string > apellido = "Martínez"
> paste(nombre, apellido) #join both data in one
The R Project for Statistical Computing http://www.r-project.org/
# Arithmetic Operators
+ addition - subtraction * multiplication / division ^ or ** exponentiation
#Logical Operators
< less than <= less than or equal to > greater than >= greater than or equal to == exactly equal to != not equal to !x Not x x | y x OR y x & y x AND y
Function Operation Performed sqrt(x) Square root of x abs(x) Absolute value sin(x), tan(x), cos(x) Trigonometric functions exp(x) Exponential log(x) Natural logarithm log10(x) Base 10 logarithm ceiling(x) Closest integer not less than x floor(x) Closest integer not greater x round(x) Closest integer to the element choose(n, k) Cn
k factorial(n) n! (n factorial)
R existing functions
The R Project for Statistical Computing http://www.r-project.org/
# Vectors > vectordatos <- c(4, 2, 3, 5, 1,6,7) > sort(vectordatos) #sort your data from smallest to largest > order(vectordatos) #which elements correspond to which order in your vector > vector1a200=c(1:200) > vector1a200 = seq(1,200) > nucleotidos = c("A", ”G", ”C", ”T") ; >nombresclase = c("Gianina","Carles", "Teresa","M Pilar","Josep","Patricia" , "Mar") >length(nombresclase) #Combining vectors > n = c(6, 2, 3, 5, 4) > s = c("aa", "bb", "cc", "dd", "ee") > c(n, s) > vectoralvuelo<-scan() #entrada de datos sobre la marcha # Vector Arithmetics > a = c(1, 3, 5, 7) ; b = c(1, 2, 4, 8); c = c(2,3) > 5 * a > a + b > b + c # Vector Index > nombresclase[4] > nombresclase[-4] > nombresclase[3:5]
The R Project for Statistical Computing http://www.r-project.org/
# Re-assigning a new value > nombresclase[4] <- "Pilar" > nombresclase > vectordatos[5] <- 4 # Named Vector Members >names(nucleotidos) = c("adenina", "guanina", "citosina", “timina") >nucleotidos # Matrices and arrays > mat<-matrix(c(2,3,1,5),nrow=2,ncol=2) > mat >nrow(mat) # Data frames > organismo<-c("Human","Mouse","Fruit Fly", "Roundworm","Yeast") > tamanogenomaBP<-c(3000000000,3000000000,135600000,97000000,12100000) > n_est_genes<-c(30000,30000,13061,19099,6034) > comparaciontamanogenoma<- data.frame(organismo=organismo, tamanogenomaBP = tamanogenomaBP, n_est_genes = n_est_genes) > comparaciontamanogenoma # Data entry editor > x= c(3.2,1.6,3.0,5.9,12.4,3.7,12.9,1.3,2.1,3.4,5.7,7.9,3.8,1.9,3.7)#lista numérica > data.entry(x) #R built in data editor to edit existing data object
Muestra
•Muestreo:
•Muestreos malos muestreo sesgado (muestro de conveniencia, de respuesta voluntaria)
•Muestreos buenos (aleatorios – aplicación ramdomizer)
•Muestreo aleatorio simple
•Muestreo aleatorio estratificado
Muestreo aleatorio simple Muestreo aleatorio estratificado
https://www.randomizer.org/
THE DATA PIPELINE
Data cleaning -> Example Sequencing techologies
Next Generation Technologies (starting in 2005) (Next Lesson):
Massively parallel sequencing ($1000 genome’ program NHGRI)
Dramatic increase of sequence output
Significant decrease in the length of reads Decrease in the accuracy of calling bases -> Very different error profiles depending on the technological platform
Analytical difficulties (profound changes in data analysis pipelines) Revitalization of bioinformatics
Calidad de los datos
THE DATA PIPELINE
Exploratory data analysis ->
Dialoga con los datos
Robert Rosenthal -> As soon as you have collected your data, before you compute any statistics, look at your data. Always plot your data, always ask were the data come from
Summary of good statistical practice
• Describe your population clearly
• Describe your data production and prefer randomized method whenever possible
• Describe your variable and how they were measured
• Give your sample size and explain how you decided on the sample size
• If were dropouts or other problems, mention them
The R Project for Statistical Computing http://www.r-project.org/
# Data descriptive measures > m = c(1, 3, 5, 7,3,4,5,3,2,3,4,9,14,5,14) #lista numérica > table(m) > table(m)/length(m) > hist(m) > hist(m, main="Histograma", xlab="Valores") > mean(m) #media > median(m) #mediana > quantile(m) #cuartiles > quantile (m, c(.4,.63,.85)) #percentil > max(m) > min(m) > var(m) > sd(m) > summary(m) > summary(comparaciontamanogenoma) #Summary of descriptive measures of matrix or data frames >a = c("C","A","G","T","A","C","G","G","C","G","A","A", "T","C","T","A") #lista datos cualitativos > table(a) > table(a)/length(a) > pie(table(a))
Exploratory Data Analysis
Exploratory Data Analysis
Data Summary Functions in R
Function name Task performed sum(x) Sums the elements in x prod(x) Product of the elements in x max(x) Maximum element in x min(x) Minimum element in x range(x) Range (min to max) of elements in x length(x) Number of elements in x mean(x) Mean (average value) of elements in x. median(x) Median (middle value) of elements in x var(x) Variance of elements in x sd(x) Standard deviation of element in x cor(x,y) Correlation between x and y quantile(x,p) The pth
quantile of x cov(x,y) Covariance between x and y
The R Project for Statistical Computing http://www.r-project.org/
# Graphs > x = seq(1,10,0.1) > plot(x,sqrt(x),type="l“) > pie(table(a)) #more on creating a graph
#Saving graphics (file menu)
The R Project for Statistical Computing http://www.r-project.org/
Function name Plot produced boxplot(x) " Box and whiskers " plot pie(x) Circular pie chart hist(x) Histogram of the frequencies of x barplot(x) Histogram of the values of x stripchart(x) Plots values of x along a line dotchart(x) Cleveland dot plot pairs(x) For a matrix x, plots all bivariate pairs plot.ts(x) Plot of x with respect to time (index values of the vector unless specified) contour(x,y,z) Contour plot of vectors x and y, z must be a matrix of dimension rows=x and columns=y image(x,y,z) Same as contour plot but uses colors instead of lines persp(x,y,z) 3-d contour plot
Selected High-Level Plotting Functions
The R Project for Statistical Computing http://www.r-project.org/
Selected Low-Level Plotting Functions
Function name Effect on plot points(x,y) Adds points lines(x,y) Adds lines text(x, y, label= " ") Adds text (label= " text ") at coordinates (x,y) segments(x0,y0,x1,y1) Draws a line from point (x0,y0) to point (x1,y1) abline(a,b) Draws a line of slope a and intercept b; also abline(y= ) and abline(x= ) will draw horizontal and vertical lines respectively. title(" ") Adds a main title to the plot; also can add additional arguments to add subtitles rug(x) Draws the data on the x-axis with small vertical lines rect(x0,y0,x1,y1) Draws a rectangle with specified limits (note – good for pointing out a certain region of the plot) legend(x,y,legend=,…) Adds a legend at coordinate x,y; axis() Adds additional axis to the current plot
# Graphs
# Working directory > getwd() # get current working directory > setwd("<new path>") # set working directory > setwd("C:/MisDocumentos") > history() > q() # quit R > objects() # track names objects created. Rm(s) # removes object s #Packages > library() # see all packages installed > search() # see packages currently loaded #Installing and Loading Packages (package menu)
#Saving your data (file menu)
#Save to file: save everything (commands and output) >savehistory(file="Mi_Sesion.Rhistory") #Savehistory: save everything typed into the command line prior to the savehistory() function call. Saved in *.Rhistory file #Saving workspace image: saves only the objects you have created (any momnet or end of a session)
The R Project for Statistical Computing http://www.r-project.org/
# Import data # Table file (values separated by blank characters) >misdatos <- read.table("misdatos.txt" , header=TRUE) >length(misdatos[[1]]) >mean(table(misdatos[9])) #alternativamente sapply(misdatos[9]),mean) o sd, var,… # Formato CSV (comma separated values) >misdatos <- read.table("misdatos.CSV", sep=",") Formato Fasta (se requiere instalación paquete SeqinR) >miseqfasta <- read.fasta("misdatos.fa") > miseqfastasep <- miseqfasta[[1]] # se lee cada carácter de la secuencia como elemento separado #(comparar función length en ambos casos) # Convertir datos en matriz a vector >datavector = c(t(as.matrix(datosmatriz))) # More on Importing data # Exporting data
The R Project for Statistical Computing http://www.r-project.org/
# Subsetting Data #Tabla de datos con 10 variables #selecting (keeping) variables # select variables v1, v2, v3 >myvars = c("v1", "v2", "v3") >newdata = mydata[myvars] # select 1st and 5th thru 10th variables >newdata = mydata[c(1,5:10)] #selecting observations # first 5 observations >newdata = mydata[1:5,] # based on variable values >newdata = mydata[ which(mydata$gender=='F' & mydata$age > 65), ] # or >attach(newdata) #objects in the database can be accessed by simply giving their names >newdata = mydata[ which(gender=='F' & age > 65),] >detach(newdata) # using subset function >newdata = subset(mydata, age >= 20 | age < 10, select=c(ID, Weight))
The R Project for Statistical Computing http://www.r-project.org/
• Instala el paquete SeqinR • Bájate las secuencias Fasta del genoma mitocondrial completo de humanos y
la rata en formato FASTA del NCBI (NC_001807 y NC_001665) • Importa el archivo con "read.fasta " • Calcula la longitud de los genomas, la proporción de nucleótidos y el
contenido de GC
ID SNP1 SNP2 SNP3 SNP4 SNP5 STATUS SEX AGE BMI 1 C/C T/T C/C C/C G/G 0-Control Female 74 [25.9,29.0) 2 C/G C/C A/A C/G G/G 0-Control Male 50 [16.0,23.6) 3 C/G T/C C/C C/C G/T 0-Control Female 64 [16.0,23.6) 4 C/C T/T C/C C/C G/G 1-Case Male 67 [16.0,23.6) 5 C/C T/T C/C C/C G/G 0-Control Female 80 [29.0,52.2] 6 C/C T/T C/C C/C G/G 0-Control Male 79 [29.0,52.2] 7 C/G T/C C/A C/G G/G 1-Case Male 83 [16.0,23.6)…
Trata de importar esta tabla (sigue el enlace), explora cada una de las variables y estima distintas medidas descriptivas. Haz la misma exploración para subgrupos (por ejemplo, mujeres mayores de 80 años,…)
SNP-Data1
Estadística del genoma mitocondrial
Obtén información sobre el paquete seqinr con el comando help("SEQINR.UTIL“)
Más datos para importa y explorar aquí
Tabla resumen genoma humano
otros datos a analizar
Trata de importar esta tabla (sigue el enlace), explora cada una de las variables y estima distintas medidas descriptivas
Solución ejercicios
snps_data = read.table("http://bioinformatica.uab.cat/base/documents/sgbcurso_inf_est/SNP-Data12015_7_7D19_20.txt", header=TRUE) sapply(snps_data[9],mean) sapply(snps_data[9],sd) summary(snps_data) summary(snps_data[1]) summary(snps_data[4:9])
mujeresmayor80 <- mydata[ which(mydata$SEX == "Female" & mydata$AGE > 80), ]
• Instala el paquete SeqinR • Bájate las secuencias Fasta del genoma mitocondrial completo de humanos y la rata en formato FASTA del NCBI
(NC_001807 y NC_001665) • Importa el archivo con "read.fasta " • Calcula la longitud de los genomas, la proporción de nucleótidos y el contenido de GC
Estadística del genoma mitocondrial
Solución ejercicios
seqmito <- read.fasta("Hsapiens_mitochondrion_genome.fa") seqmitosep = seqmito[[1]] length(seqmito) table(seqmito) table(seqmitosep)/length(seqmitosep) # prob each nucleotide rho (seqmitosep,2) count(seqmitosep,1) GC(seqmitosep) #GC content count(seqmitosep,2) count(seqmitosep,2) / sum(count(seqmitosep,2)) # prob_each dinucleotide rho (seqmitosep,2) zscore(eqmitosep,model="base“)
# Sample function > sample(1:10,3) > sample(seq(1,15),8) > sample(2:30,10, replace=T) > sample(1:5,10, prob=c(0.3,0.4,0.1,0.1,0.1), replace = T) > sample(nombresclase,50, replace = T) > color = c("R", "V") > prob=c(0.66,0.33) > muestra2cl10n= sample(color,10, prob, replace = T) > table(muestra2cl10n) # Sample a DNA sequence > nucleotide = c("A","C","T","G") > prob = c(0.3,0.2,0.4,0.1) > nsample = 100 > sample(nucleotide,nsample,prob,replace=T) >nsample = 1000 > sequence1000 =sample(nucleotide,nsample,prob,replace=T) > table(sequence1000) > table(sequence1000)/ nsample
Muestreo aleatorio (simulación) con R
• Simula resultados de un cruce mendeliano Aa x Aa para n=10, 50, 1000 descendientes. Estima la proporción del genotipo AA en cada caso
Resp: > genotipo = c("AA", "noAA") > prob=c(0.25,0.75) > nmuestra = 10 > muestragenAA= sample(genotipo,nmuestra,prob,replace = T) > muestragenAA >propAA=table(muestragenAA)/nmuestra >propAA
• Simula las respuestas (Correctas, Incorrectas) de un test de respuesta múltiple (4
respuestas por preguntas) de 10, 100, 1000 preguntas. Cuál es la nota obtenida en cada caso (con y sin penalización de ¼) Resp: > respuestas = c("Corr", "Iconrr") > prob=c(0.25,0.75) >notaresp= c(1,-0.25) > nmuestra = 10 > muestraresp= sample(respuestas,nmuestra,prob,replace = T) >nota= sum(table(muestraresp)*nota)/nmuestra Trata de relacionar los resultados de los ejercicios previos con una famosa ley de la estadística
• Genera una secuencia de 500 nucleótidos que siga una distribución multinomial
con equiprobabilidad para cada nucleótido.
• El mismo ejercicio que el anterior pero con la probabilidades por nucleótidos calculadas en el genoma mitocondrial humano
Frecuencia de caras al lanzar una moneda sucesivamente
Ley de los grandes número
Demostrar mediante simulación la ley de los grandes número Nota: la demostración puede hacerse simulando el lanzamiento de un dado o moneda, el resultado de un cruce mendeliano,…
> prob = c(0.5,0.5) #lanzamiento una moneda misma probabilidad > moneda = c(1,0) #1 cara y 0 cruz (valores numéricos para obtener probabilidad directamente) > nsample = c(1:200) #los datos muestreados se incrementa en cada nuevo muestreo > nreplica = 200 #número muestras simuladas > vector_media = c(1:nreplica) > for (i in 1: nreplica){vector_media[i]=mean(sample(moneda,nsample[i],prob,replace=T))} #bucle vector probabilidad > vector_media > plot(vector_media, main="Ley grandes números", xlab="Número tiradas", ylab="Proporción Caras")
Solución: Ley grandes números demostrada mediante simulación
de la frecuencia de caras al lanzar una moneda sucesivamente
Bucle (Loop) for (i in start:finish) Ejecuta función >y =c(1:10) >for (i in 1:10){ y[i]= sqrt(i)}