Friday 4 August 2017

Análise descritiva em stata forex


Os resultados das suas análises estatísticas ajudam a compreender o resultado do seu estudo, p. Se alguma variável tem algum efeito, se as variáveis ​​estão relacionadas, se as diferenças entre grupos de observações são iguais ou diferentes, etc. As estatísticas são ferramentas da ciência, não um fim para si mesmas. Estatísticas devem ser usadas para fundamentar suas descobertas e ajudá-lo a dizer objetivamente quando você tem resultados significativos. Portanto, ao relatar os resultados estatísticos relevantes para o seu estudo, subordiná-los aos resultados biológicos reais. Relatórios Descritivos (Sumário) Estatísticas Meios. Sempre informe a média (valor médio) juntamente com uma medida de variabilidade (desvio padrão (s) ou erro padrão da média). Dois modos comuns de expressar a média ea variabilidade são mostrados abaixo: O comprimento total da truta marrom (n128) média de 34,4 cm (s 12,4 cm) em maio de 1994, amostras de Sebago Lake. quot s desvio padrão (este formato é preferido por Huth E outros (1994) quotTotal comprimento de truta marrom (n128) em média 34,4 plusmn 12,4 cm em maio de 1994, amostras de Sebago Lake. quot Este estilo necessita especificamente dizendo nos Métodos que a medida da variabilidade é relatada com a média. Se o resumo As estatísticas são apresentadas em forma gráfica (uma figura), você pode simplesmente relatar o resultado no texto sem verbalizar os valores de resumo: quotMean comprimento total de truta marrom em Sebago Lake aumentou 3,8 cm entre maio e setembro de 1994 (Figura 5) Frequências: Os dados de frequência devem ser resumidos no texto com medidas apropriadas, tais como percentagens, proporções ou proporções. Quanto ao período de giro de queda, estima-se que 47 de trutas marrons e 24 de ribeiro se concentraram nas partes mais profundas do lago (Tabela 3).quot Relatando Resultados de Testes Inferenciais (Hipóteses) Neste exemplo, o resultado chave é mostrado em azul eo resultado estatístico. Que comprova a descoberta, está em vermelho. O comprimento total médio de truta marrom no lago Sebago aumentou significativamente (3,8 cm) entre maio (34,4 mais 12,4 cm, n128) e setembro (38,2 mais 11,7 cm, n 114) 1994 (teste twosample t, p lt 0,001). NOTA : EVITE escrever frases inteiras que simplesmente digam qual teste você usou para analisar um resultado seguido por outro dando o resultado. Isto desperdiça palavras preciosas (economia.) E aumenta desnecessariamente seu comprimento dos papéis. Resumindo Resultados de Testes Estatísticos em Figuras Se os resultados mostrados em uma figura tiverem sido testados com um teste inferencial, é apropriado resumir o resultado do teste no gráfico para que o leitor possa compreender rapidamente o significado dos achados. É imperativo que você inclua informações em seus Materiais e Métodos, ou na legenda da figura, para explicar como interpretar qualquer sistema de codificação que você usa. Vários métodos comuns para resumir resultados estatísticos são mostrados abaixo. Exemplos: Comparação de grupos (testes t, ANOVA, etc.) A comparação das médias de 2 ou mais grupos é normalmente representada num gráfico de barras das médias e barras de erro associadas. Para dois grupos. A média maior pode ter 1-4 asteriscos centrados sobre a barra de erro para indicar o nível relativo do valor p. Em geral, quotquot significa plt 0,05, quot significa plt 0,01, quot significa plt 0,001 e quot significa plt0,0001. Em todos os casos, o p-valor deve ser relatado também na figura legenda O asterisco também pode ser usado com resultados tabulares como mostrado abaixo. Observe como o autor usou uma nota de rodapé para definir os valores de p que correspondem ao número de asteriscos. (Cortesia de Shelley Ball) Para três ou mais grupos existem dois sistemas normalmente utilizados: linhas ou letras. O sistema que você usa depende de como é complicado resumir o resultado. O primeiro exemplo abaixo mostra uma comparação de três meios. A linha que atravessa duas barras adjacentes indica que não são significativamente diferentes (com base num teste de comparações múltiplas) e porque a linha não inclui a média de pH 2, indica que a média de pH 2 é significativamente diferente do pH 5,3 ( Controlo) e o grupo de pH 3,5 significa. Observe que as informações sobre como interpretar o sistema de codificação (linha ou letras) estão incluídas na legenda da figura. Quando as linhas não podem ser facilmente desenhadas para resumir o resultado, a alternativa mais comum é usar letras maiúsculas colocadas sobre as barras de erro. As cartas compartilhadas em comum entre os grupos indicariam nenhuma diferença significativa. Exemplo: Resumindo Análises de Correlação e Regressão Para dados de relacionamento (parcelas X, Y) nos quais uma análise de correlação ou regressão foi realizada, é costume reportar as estatísticas de teste salientes (por exemplo, r, r-quadrado) e p-valor em O corpo do gráfico em fonte relativamente pequena, de modo a ser discreto. Se uma regressão é feita, a linha de melhor ajuste deve ser plotada ea equação da linha também fornecida no corpo do gráfico. Alterado 1-11-2012 Departamento de Biologia, Bates College. Lewiston, ME 04240 Exemplo de regressão, parte 1: análise descritiva Qualquer análise de regressão (ou qualquer tipo de análise estatística, para esse assunto) deve começar com um olhar atento sobre a matéria-prima: os dados. De onde ele veio, como foi medido, está limpo ou sujo, quantas observações estão disponíveis, quais são as unidades, quais são as magnitudes e os intervalos típicos dos valores e, muito importante, como as variáveis ​​se parecem. Grande parte do seu cérebro é dedicada ao processamento de informações visuais, e a incapacidade de envolver essa parte de seu cérebro é como disparar no escuro. A análise visual ajuda a identificar padrões sistemáticos, bem como eventos e erros de dados incomuns. O objetivo desta análise será explicar e prever como a quantidade de vendas semanais de uma marca de cerveja popular depende de seu preço em uma pequena cadeia de supermercados. O arquivo de dados contém 52 semanas de registros de preços médios e de vendas totais para três tamanhos diferentes de cartões: 12-packs, 18-packs e 30-packs. Uma das primeiras coisas a considerar na montagem de um conjunto de dados para análise de regressão é a escolha de unidades (ou seja, dimensionamento) para as variáveis. No final do dia você estará olhando para medidas de erro que são expressas nas unidades da variável dependente, e os coeficientes do modelo serão medidos em unidades de mudança prevista na variável dependente por unidade de mudança na variável independente. Idealmente, estes números devem ser dimensionados de uma forma que os torna fáceis de ler e fáceis de interpretar e comparar. Nesta análise, as variáveis ​​preço e vendas já foram convertidas para uma base por caso (isto é, por 24 unidades). De modo a que os volumes de vendas relativos para diferentes tamanhos de cartão sejam directamente comparáveis ​​e que os coeficientes de regressão sejam directamente comparáveis ​​para modelos adaptados a dados para diferentes tamanhos de cartões. As primeiras linhas do conjunto de dados (em um arquivo do Excel) se parecem com isto: Os cabeçalhos das colunas foram escolhidos para serem adequados como nomes de variáveis ​​descritivas para a análise. O valor de 19,98 para PRICE12PK na semana 1 significa que 24 latas de cerveja custam 19,98 quando compradas em 12 embalagens naquela semana (ou seja, o preço de um único pacote de 12 era de 9,99) eo valor de 223,5 para CASES12PK significa que 447 12- Pacotes foram vendidos (porque um caso é de dois 12-packs). A partir daí, observa-se a estatística descritiva, que mostra as magnitudes típicas e os intervalos das variáveis: Aqui se observa que o volume de vendas (medido em unidades comparáveis ​​de casos) foi maior para os tamanhos de cartões menores (399 casos8217 no valor de 12- Em comparação com 165 para 30 embalagens, com 18 pacotes no meio), enquanto o preço médio por caixa foi significativamente menor para os tamanhos de cartões maiores (14,38 por caixa em média para 30 embalagens, contra 19,09 por caixa Para 12-packs, com 18-packs novamente no meio). No entanto, verificou-se uma variação considerável nos preços de cada tamanho de cartão, tal como demonstrado pelos valores mínimo e máximo. Como essas são variáveis ​​de séries temporais, é de vital importância examinar os gráficos de séries temporais. como mostrado abaixo. (Na verdade, você deve olhar para as parcelas de suas variáveis ​​versus número de linha, mesmo se eles não são séries de tempo Você nunca sabe o que você pode ver. Para não-série de dados em série, você não iria querer desenhar linhas de conexão entre os pontos, no entanto. ) O que se destaca claramente nestas parcelas é que (como os compradores de cerveja confirmarão) os preços de diferentes tamanhos de cartões são sistematicamente manipulados de semana para semana em uma ampla gama, e há picos de vendas em semanas onde há cortes de preços. Por exemplo, houve um corte profundo no preço de 18 pacotes nas semanas 13 e 14, e um grande aumento correspondente nas vendas nessas duas semanas. Na verdade, se você olhar para todos os casos-vendidos parcelas, você pode ver que o volume de vendas para cada tamanho de cartão é bastante baixo, a menos que seu preço é cortado em uma determinada semana. Outra coisa que se destaca é o padrão de manipulação de preços não era o mesmo para todos os tamanhos de cartão. Os preços dos pacotes de 12 não foram manipulados muito frequentemente, enquanto os preços dos pacotes de 30 foram manipulados quase semana após semana no primeiro semestre do ano e os preços dos pacotes de 18 foram mais manipulados no segundo semestre Do ano. Então, neste ponto, temos uma boa idéia do que os padrões qualitativos estão em preços e vendas semanais. Se nosso objetivo é medir as relações preço-demanda ajustando modelos de regressão, também estamos muito interessados ​​nas correlações entre as variáveis ​​e na aparência de seus diagramas de dispersão. Aqui está a matriz de correlação, isto é, a tabela de todas as correlações pairwise entre as variáveis. (Lembre-se que a correlação entre duas variáveis ​​é uma estatística que mede a força relativa da relação linear entre elas em uma escala de -1 a 1.) O que se destaca claramente aqui é que (como já sabíamos ao olhar para o tempo Séries), existem correlações negativas muito fortes entre o preço e as vendas para os três tamanhos de cartão (maior que 0,8 na magnitude, como se verifica), que são medidas da elasticidade-preço da demanda.8221 Há também algumas correlações positivas mais fracas Entre o preço de um cartão e as vendas de outro - por exemplo, uma correlação de 0,521 entre o preço de 18 embalagens e as vendas de 30 embalagens. Estas são medidas de elasticidades de preço cruzado8221, ou seja, efeitos de substituição. Os consumidores tendem a comprar menos embalagens de 30 quando o preço de 18 embalagens é reduzido, presumivelmente porque eles compram 18 embalagens em vez disso. Por último, mas não menos importante, devemos olhar para a matriz de dispersão de dispersão das variáveis, isto é, a matriz de todos os diagramas de dispersão de 2 vias. A matriz do diagrama de dispersão é a contrapartida visual da matriz de correlação e deve ser sempre estudada como um prelúdio à análise de regressão se houver muitas variáveis. (Praticamente todos os softwares de regressão comercial oferecem esse recurso, embora os resultados variem muito em termos de qualidade gráfica Os produzidos por RegressIt, que são mostrados aqui, incluem opcionalmente a linha de regressão, ponto de centro de massa, correlação e quadrado A matriz de dispersão completa para estas variáveis ​​é uma matriz 6x6, mas estamos especialmente interessados ​​na submatrix 3x3 de scatterplots em que o volume de vendas é plotado vs preço para diferentes combinações de tamanhos de cartão: Cada uma dessas parcelas mostra não apenas a relação preço-demanda para as vendas de um tamanho de cartão versus o preço de outro, mas também dá uma prévia dos resultados que serão obtidos se um modelo de regressão simples for ajustado. Nas páginas que se seguem, modelos de regressão serão ajustados aos dados de vendas de 18 pacotes. A partir do diagrama de dispersão no centro da matriz, já sabemos muito sobre os resultados que obteremos se regressarmos as vendas de 18 pacotes no preço de 18 pacotes. No entanto, algumas bandeiras vermelhas8221 já estão acenando neste ponto. Os relacionamentos preço-demanda são bastante fortes, mas a variação das vendas não é consistente em toda a gama de preços em nenhuma dessas parcelas. A propósito, toda a saída mostrada acima foi gerada ao mesmo tempo em uma única planilha do Excel com algumas teclas digitadas usando o procedimento de Análise de Dados em RegressIt, como mostrado abaixo. Esperamos que o seu software fará isso relativamente fácil too. Welcome para o Instituto de Pesquisa Digital e Educação SAS Seminário Introdução à Análise de Sobrevivência no SAS 1. Introdução Análise de sobrevivência modelos fatores que influenciam o tempo para um evento. Os métodos ordinários de regressão por mínimos quadrados ficam aquém porque o tempo até o evento normalmente não é distribuído, eo modelo não consegue lidar com a censura, muito comum nos dados de sobrevivência, sem modificações. Métodos não paramétricos fornecem uma visão simples e rápida da experiência de sobrevivência, eo modelo de regressão proporcional de riscos de Cox continua a ser o método de análise dominante. Este seminário apresenta procedimentos e descreve a codificação necessária no SAS para modelar dados de sobrevivência através destes dois métodos, bem como muitas técnicas para avaliar e possivelmente melhorar o modelo. Uma ênfase particular é dada a proc lifetest para estimativa não paramétrica, e proc phreg para regressão de Cox e avaliação de modelo. Nota: Uma série de sub-seções são intituladas Background. Estes fornecem alguns antecedentes estatísticos para análise de sobrevivência para o leitor interessado (e para o autor do seminário). Desde que o leitor tenha alguma experiência em análise de sobrevivência, essas seções não são necessárias para entender como executar a análise de sobrevivência em SAS. Estes podem ser removidos ou expandidos no futuro. Nota: Os termos evento e falha são usados ​​de forma intercambiável neste seminário, assim como tempo para evento e tempo de falha. 1.1 Amostra de dados Neste seminário estaremos analisando os dados de 500 indivíduos do Worcester Heart Attack Study (doravante denominado WHAS500, distribuído com Hosmer Lemeshow (2008)). Este estudo examinou vários fatores, como idade, sexo e IMC, que podem influenciar o tempo de sobrevivência após um ataque cardíaco. O tempo de seguimento para todos os participantes começa no momento da admissão no hospital após um ataque cardíaco e termina com a morte ou perda de seguimento (censura). As variáveis ​​utilizadas no presente seminário são: lenfol: duração do seguimento, terminada por morte ou censura. O resultado deste estudo. Fstat: variável de censura, perda de seguimento0, óbito1 idade: idade de internação bmi: índice de massa corporal hr: freqüência cardíaca inicial gênero: machos0, sexo feminino1 Os dados no WHAS500 estão sujeitos apenas à censura à direita. Ou seja, para alguns sujeitos que não sabemos quando eles morreram após um ataque cardíaco, mas sabemos pelo menos quantos dias eles sobreviveram. 1.2. A compreensão da mecânica por trás da análise de sobrevivência é auxiliada pela facilidade com as distribuições utilizadas, que podem ser derivadas da função de densidade de probabilidade e funções de densidade cumulativa dos tempos de sobrevivência. 1.2.1. A função de densidade de probabilidade, f (t) Imagine que temos uma variável aleatória, Time, que registra os tempos de sobrevivência. A função que descreve a probabilidade de observar o Tempo no tempo t relativo a todos os outros tempos de sobrevivência é conhecida como função de densidade de probabilidade (pdf), ou f (t). A integração do pdf em um intervalo de tempo de sobrevivência dá a probabilidade de observar um tempo de sobrevivência dentro desse intervalo. Por exemplo, se os tempos de sobrevivência eram conhecidos como exponencialmente distribuídos, então a probabilidade de observar um tempo de sobrevivência dentro do intervalo a, b é Pr (ale Timele b) intabf (t) dtintablambda e dt, onde lambda é o parâmetro de taxa de A distribuição exponencial e é igual ao recíproco do tempo médio de sobrevivência. Na maioria das vezes não saberemos a priori a distribuição gerando nossos tempos de sobrevivência observados, mas podemos obter e idéia do que parece usar métodos não paramétricos em SAS com proc univariada. Aqui vemos o pdf estimado de tempos de sobrevivência no conjunto whas500, do qual todas as observações censuradas foram removidas para auxiliar apresentação e explicação. No gráfico acima vemos a correspondência entre pdfs e histogramas. As funções de densidade são essencialmente histogramas compreendendo caixas de pequenas larguras. No entanto, em ambos podemos ver que nestes dados, os tempos de sobrevivência mais curtos são mais prováveis, indicando que o risco de ataque cardíaco é forte inicialmente e diminui com o passar do tempo. (Tecnicamente, porque não há tempos menores que 0, não deve haver nenhum gráfico à esquerda de LENFOL0) 1.2.2. A função de distribuição cumulativa (cdf), F (t), descreve a probabilidade de observar Tempo menor ou igual a algum tempo t, ou Pr (Timele t). Acima descrevemos que a integração do pdf sobre alguma faixa produz a probabilidade de observar o Tempo nessa faixa. Assim, definimos a função de distribuição cumulativa como: Como exemplo, podemos usar o cdf para determinar a probabilidade de observar um tempo de sobrevivência de até 100 dias. A relação acima entre o cdf eo pdf também implica: No SAS, podemos graficar uma estimativa do cdf usando proc univariável. No gráfico acima podemos ver que a probabilidade de sobreviver a 200 dias ou menos é de cerca de 50. Assim, por 200 dias, um paciente tem acumulado um pouco de risco, que se acumula mais lentamente após este ponto. Em intervalos onde os tempos de eventos são mais prováveis ​​(aqui os intervalos iniciais), o cdf irá aumentar mais rapidamente. 1.2.3. A função de sobrevivência, S (t), descreve a probabilidade de sobreviver após o tempo t, ou Pr (Tempo), a função de sobrevivência, S (t) T). Se estivéssemos a traçar a estimativa de S (t), veríamos que é um reflexo de F (t) (sobre y0 e deslocado para cima por 1). Aqui usamos proc lifetest para representar S (t). Parece que a probabilidade de sobreviver além de 1000 dias é um pouco menos de 0,2, o que é confirmado pelo cdf acima, onde vemos que a probabilidade de sobreviver 1000 dias ou menos é um pouco mais de 0,8. 1.2.4. O foco principal da análise de sobrevivência é tipicamente modelar a taxa de risco, que tem a seguinte relação com f (t) e S (t): A função de perigo, então, descreve a relação relativa Probabilidade de ocorrência do evento no tempo t (f (t)), condicionada à sobrevivência dos indivíduos até esse tempo t (S (t)). A taxa de risco descreve assim a taxa instantânea de falha no instante t e ignora a acumulação de perigo até ao tempo t (ao contrário de F (t) e S (t)). Podemos estimar a função de risco é SAS, bem como usar proc lifetest: Como vimos antes, o perigo parece ser maior no início do tempo de acompanhamento e, em seguida, rapidamente diminui e finalmente níveis de fora. Na verdade, a taxa de risco no início é mais de 4 vezes maior do que o risco 200 dias depois. Assim, no início do estudo, seria de esperar cerca de 0,008 falhas por dia, enquanto 200 dias mais tarde, para aqueles que sobreviveram, seria de esperar 0,002 falhas por dia. 1.2.5. Antecedentes: A função de risco cumulativo Também é útil entender é a função de risco cumulativo, que como o nome implica, cumula riscos ao longo do tempo. É calculado integrando a função de perigo ao longo de um intervalo de tempo: Pensemos novamente na função de perigo, h (t), como a taxa na qual as falhas ocorrem no tempo t. Suponhamos ainda, para fins ilustrativos, que a taxa de perigo permanece constante na frac (x número de falhas por unidade de tempo t) ao longo do intervalo 0, t. Soma em todo o intervalo, então, seria de esperar para observar falhas x, como frac t x, (assumindo falhas repetidas são possíveis, de modo que falha não remove um da observação). Uma interpretação da função de risco cumulativo é, portanto, o número esperado de falhas ao longo do intervalo de tempo 0, t. Não é absolutamente necessário que a função de perigo permaneça constante para a interpretação acima da função de perigo acumulada, mas para fins ilustrativos é mais fácil calcular o número esperado de falhas, uma vez que a integração não é necessária. Expressando a relação acima como frac H (t) h (t), vemos que a função de perigo descreve a taxa na qual os perigos se acumulam ao longo do tempo. Usando as equações, h (t) frac e f (t) - frac, podemos derivar as seguintes relações entre a função de risco cumulativo e as outras funções de sobrevivência: A partir dessas equações podemos ver que a função cumulativa de risco H (t) e A função de sobrevivência S (t) tem uma relação monotônica simples, de modo que quando a função de Sobrevivência está no seu máximo no início do tempo de análise, a função de risco cumulativo está no seu mínimo. À medida que o tempo avança, a função de Sobrevivência prossegue para ele mínimo, enquanto a função de perigo cumulativo prossegue para seu máximo. A partir dessas equações também podemos ver que seria esperado que o pdf, f (t), seja alto quando h (t) a taxa de risco é alta (o início, neste estudo) e quando o hazard cumulativo H (t) é Baixo (o início, para todos os estudos). Em outras palavras, esperamos encontrar muitos tempos de falha em um dado intervalo de tempo se 1) a taxa de risco for alta e 2) ainda houver muitos sujeitos em risco. Podemos estimar a função de perigo cumulativo usando proc lifetest. Os resultados dos quais enviamos para proc sgplot para plotagem. Vemos um aumento mais acentuado no risco cumulativo no início do tempo de análise, refletindo a maior taxa de risco durante esse período. 2. Preparação e exploração dos dados 2.1. Estrutura dos dados Este seminário cobre tanto proc lifetest quanto proc phreg. E os dados podem ser estruturados em uma das duas formas de análise de sobrevivência. Em primeiro lugar, pode haver uma linha de dados por assunto, com uma variável de resultado representando o tempo até o evento, uma variável que codifica se o evento ocorreu ou não (censurado) e variáveis ​​explicativas de interesse, cada uma com valores fixos em seguimento Tempo. Ambos proc lifetest e proc phreg aceitarão dados estruturados desta forma. Os dados WHAS500 são estruturados desta forma. Observe que há uma linha por assunto, com uma variável codificando o tempo para o evento, lenfol: Nós vemos na tabela acima, que o sujeito típico em nosso conjunto de dados é mais provável masculino, 70 anos de idade, com um bmi de 26,6 e coração Taxa de 87. O tempo médio para o evento (ou perda para acompanhamento) é 882,4 dias, não uma quantidade particularmente útil. Todas essas variáveis ​​variam um pouco nesses dados. A maioria das variáveis ​​são pelo menos ligeiramente correlacionadas com as outras variáveis. 3. Análise de sobrevivência não-paramétrica (descritiva) usando proc lifetest 3.1. O estimador de Kaplan Meier da função de sobrevivência 3.1.1 Antecedentes: O estimador de Kaplan Meier: O estimador da função de sobrevivência de KaplanMeier é calculado como: onde ni é o número de sujeitos em risco e di é o número de sujeitos que falham, Ti Assim, cada termo no produto é a probabilidade condicional de sobrevivência além do tempo ti, significando a probabilidade de sobreviver além do tempo ti, dado que o sujeito tem sobrevivido até o tempo ti. A estimativa da função de sobrevivência da probabilidade incondicional de sobrevivência para além do tempo t (a probabilidade de sobrevivência para além do tempo t desde o início do risco) é então obtida pela multiplicação destas probabilidades condicionais até ao tempo t em conjunto. Observando a tabela de Estimativas de Sobrevivência de Limite de Produto abaixo, para o primeiro intervalo, de 1 dia até pouco antes de 2 dias, ni 500, di 8, então hat S (1) frac 0.984. A probabilidade de sobreviver ao próximo intervalo, de 2 dias a pouco antes de 3 dias durante o qual outras 8 pessoas morreram, dado que o sujeito sobreviveu 2 dias (a probabilidade condicional) é frac 0.98374. A probabilidade incondicional de sobreviver além de 2 dias (desde o início do risco) é então S (2) frac timesfrac 0,984x0,98374,9680 3.1.2. A análise de sobrevivência muitas vezes começa com o exame da experiência de sobrevivência global através de métodos não-paramétricos, como Kaplan-Meier (produto-limite) e estimadores de vida-tabela da função de sobrevivência. Métodos não-paramétricos são atraentes porque não é necessário assumir a forma da função de sobrevivência nem da função de perigo. No entanto, os métodos não paramétricos não modelam a taxa de risco diretamente nem estimam a magnitude dos efeitos das covariáveis. No código abaixo, mostramos como obter uma tabela e um gráfico do estimador de Kaplan-Meier da função de sobrevivência de proc lifetest: A um mínimo proc lifetest requer especificação de uma variável de tempo de falha, aqui lenfol. Na instrução de tempo. Sem mais especificações, a SAS assumirá que todos os tempos relatados são falhas não censuradas, verdadeiras. Assim, como muitas observações no WHAS500 são censuradas à direita, também precisamos especificar uma variável de censura eo código numérico que identifica uma observação censurada, que é realizada abaixo com fstat (0). Todos os números entre parênteses são tratados como indicadores de censura, o que implica que todos os números excluídos dos parênteses são tratados como indicadores de que o evento ocorreu. Também especificamos a opção atrisk na instrução proc lifetest para exibir o número em risco na nossa amostra em vários pontos de tempo. Estimativas de Sobrevivência de Produto-Limite Acima vemos a tabela de estimativas de Kaplan-Meier da função de sobrevivência produzida por proc lifetest. Cada linha da tabela corresponde a um intervalo de tempo, começando no momento na coluna LENFOL para essa linha e terminando imediatamente antes da hora na coluna LENFOL na primeira linha subseqüente que tem um valor LENFOL diferente. Por exemplo, o intervalo de tempo representado pela primeira linha é de 0 dias a pouco antes de 1 dia. Neste intervalo, podemos ver que tivemos 500 pessoas em risco e que ninguém morreu, como Eventos Observados é igual a 0 ea estimativa da função de Sobrevivência é de 1.0000. Durante o intervalo seguinte, de 1 dia a pouco antes de 2 dias, 8 pessoas morreram, indicadas por 8 linhas de LENFOL1.00 e por Eventos Observados8 na última linha onde LENFOL1.00. É importante notar que as probabilidades de sobrevivência listadas na coluna Survival são incondicionais. E devem ser interpretadas como a probabilidade de sobrevivência desde o início do tempo de seguimento até ao número de dias na coluna LENFOL. Vamos dar uma olhada nos tempos de sobrevivência mais recentes na tabela: Estimativas de Sobrevivência do Produto Limite De LENFOL368 para 376, vemos que existem vários registros onde não aparece eventos. Estas são de fato observações censuradas, indicadas adicionalmente pela aparição na segunda coluna não marcada. Os sujeitos que são censurados após um determinado ponto de tempo contribuem para a função de sobrevivência até que eles abandonam o estudo, mas não são contados como uma falha. Podemos ver isso refletido na estimativa da função de sobrevivência para LENFOL382. Durante o intervalo 382,385), um dos 355 sujeitos em risco morreu, proporcionando uma probabilidade condicional de sobrevivência (a probabilidade de sobrevivência no intervalo dado, dado que o sujeito sobreviveu até o início do intervalo) neste intervalo de fração 0,9972. Vemos que a probabilidade uncoditional de sobreviver além de 382 dias é .7220, já que o chapéu S (382) 0.7220p (dias sobreviventes) vezes0.9971831, podemos resolver para p (dias sobreviventes) frac .7240. Na tabela acima, vemos que a probabilidade sobreviveu além de 363 dias 0,7240, a mesma probabilidade do que calculamos para sobreviver até 382 dias, o que implica que as observações censuradas não alteram as estimativas de sobrevivência quando deixam o estudo, Número em risco. 3.1.3. Graficando a estimativa de Kaplan-Meier Os gráficos da estimativa de Kaplan-Meier da função de sobrevivência nos permitem ver como a função de sobrevivência muda ao longo do tempo e, felizmente, são muito fáceis de gerar no SAS: Por padrão, proc lifetest grava a estimativa de Kaplan Meier, mesmo Sem a opção plot na instrução proc lifetest, então poderíamos ter usado o mesmo código de cima que produziu a tabela de estimativas de Kaplan-Meier para gerar o gráfico. No entanto, gostaríamos de adicionar faixas de confiança eo número em risco para o gráfico, então adicionamos plotssurvival (atrisk cb). A forma de função de etapa da função de sobrevivência é aparente no gráfico da estimativa de Kaplan-Meier. Quando um sujeito morre em um ponto de tempo específico, a função de passo cai, enquanto entre os tempos de falha o gráfico permanece plano. A função de sobrevivência cai mais acentuadamente no início do estudo, sugerindo que a taxa de risco é mais alta imediatamente após a hospitalização durante os primeiros 200 dias. As observações censuradas são representadas por carrapatos verticais no gráfico. Observe que a probabilidade de sobrevivência não muda quando encontramos uma observação censurada. Como a observação com o maior tempo de seguimento é censurada, a função de sobrevivência não atingirá 0. Em vez disso, a função de sobrevivência permanecerá na probabilidade de sobrevivência estimada no intervalo anterior. A função de sobrevivência é indefinida após este intervalo final em 2358 dias. A área azul-sombreada ao redor da curva de sobrevivência representa a faixa de confiança de 95, aqui bandas de confiança Hall-Wellner. Esta banda de confiança é calculada para toda a função de sobrevivência, e em qualquer intervalo dado deve ser mais amplo do que o intervalo de confiança pontual (o intervalo de confiança em torno de um único intervalo) para garantir que 95 de todos os intervalos de confiança pontuais estejam contidos nesta faixa. Muitas transformações da função sobrevivente estão disponíveis para formas alternativas de calcular intervalos de confiança através da opção conftype, embora a maioria das transformações produza intervalos de confiança muito semelhantes. 3.2. Estimador de Nelson-Aalen da função de risco cumulativo Devido à sua relação simples com a função de sobrevivência, S (t) e, a função de risco cumulativo pode ser usada para estimar a função de sobrevivência. O estimador de Nelson-Aalen é um estimador não-paramétrico da função de risco cumulativo e é dado por: onde di é o número que falhou de ni em risco no intervalo ti. O estimador é calculado, então, somando a proporção de pessoas em risco que falharam em cada intervalo até o tempo t. O estimador de Nelson-Aalen é solicitado no SAS através da opção nelson na instrução proc lifetest. A SAS apresentará as estimativas de Kaplan Meier da função de sobrevivência e as estimativas de Nelson-Aalen da função de risco cumulativo numa tabela. Função de Sobrevivência e Taxa de Risco Cumulativo Vamos confirmar a nossa compreensão do cálculo do estimador de Nelson-Aalen calculando o risco cumulativo estimado no dia 3: hat H (3) frac frac frac 0.0385, que corresponde ao valor na tabela. A interpretação desta estimativa é que esperamos 0.0385 falhas (por pessoa) no final de 3 dias. A estimativa de sobrevivência para além de 3 dias com base nesta estimativa de Nelson-Aalen do risco cumulativo seria então S (3) exp (-0,0385) 0,9623. This matches closely with the Kaplan Meier product-limit estimate of survival beyond 3 days of 0.9620. One can request that SAS estimate the survival function by exponentiating the negative of the Nelson-Aalen estimator, also known as the Breslow estimator, rather than by the Kaplan-Meier estimator through the methodbreslow option on the proc lifetest statement. In very large samples the Kaplan-Meier estimator and the transformed Nelson-Aalen (Breslow) estimator will converge. 3.3. Calculating median, mean, and other survival times of interest in proc lifetest Researchers are often interested in estimates of survival time at which 50 or 25 of the population have died or failed. Because of the positive skew often seen with followup-times, medians are often a better indicator of an average survival time. We obtain estimates of these quartiles as well as estimates of the mean survival time by default from proc lifetest. We see that beyond beyond 1,671 days, 50 of the population is expected to have failed. Notice that the interval during which the first 25 of the population is expected to fail, 0,297) is much shorter than the interval during which the second 25 of the population is expected to fail, 297,1671). This reinforces our suspicion that the hazard of failure is greater during the beginning of follow-up time. 95 Confidence Interval 3.4. Comparing survival functions using nonparametric tests Suppose that you suspect that the survival function is not the same among some of the groups in your study (some groups tend to fail more quickly than others). One can also use non-parametric methods to test for equality of the survival function among groups in the following manner: When provided with a grouping variable in a strata statement in proc lifetest. SAS will produce graphs of the survival function (unless other graphs are requested) stratified by the grouping variable as well as tests of equality of the survival function across strata. For example, we could enter the class (categorical) variable gender on the strata statement to request that SAS compare the survival experiences of males and females. Test of Equality over Strata In the graph of the Kaplan-Meier estimator stratified by gender below, it appears that females generally have a worse survival experience. This is reinforced by the three significant tests of equality. 3.4.1. Background: Tests of equality of the survival function In the output we find three Chi-square based tests of the equality of the survival function over strata, which support our suspicion that survival differs between genders. The calculation of the statistic for the nonparametric Log-Rank and Wilcoxon tests is given by. where d is the observed number of failures in stratum i at time tj, hat e is the expected number of failures in stratum i at time tj, hat v is the estimator of the variance of d , and wi is the weight of the difference at time tj (see Hosmer and Lemeshow(2008) for formulas for hat e and hat v ). In a nutshell, these statistics sum the weighted differences between the observed number of failures and the expected number of failures for each stratum at each timepoint, assuming the same survival function of each stratum. In other words, if all strata have the same survival function, then we expect the same proportion to die in each interval. If these proportions systematically differ among strata across time, then the Q statistic will be large and the null hypothesis of no difference among strata is more likely to be rejected. The log-rank and Wilcoxon tests in the output table differ in the weights wj used. The log-rank or Mantel-Haenzel test uses wj 1, so differences at all time intervals are weighted equally. The Wilcoxon test uses wj nj, so that differences are weighted by the number at risk at time tj, thus giving more weight to differences that occur earlier in followup time. Other nonparametric tests using other weighting schemes are available through the test option on the strata statement. The -2Log(LR) likelihood ratio test is a parametric test assuming exponentially distributed survival times and will not be further discussed in this nonparametric section. 3.5. Nonparametric estimation of the hazard function Standard nonparametric techniques do not typically estimate the hazard function directly. However, we can still get an idea of the hazard rate using a graph of the kernel-smoothed estimate. As the hazard function h(t) is the derivative of the cumulative hazard function H(t), we can roughly estimate the rate of change in H(t) by taking successive differences in hat H(t) between adjacent time points, Delta hat H(t) hat H(tj) - hat H(t ). SAS computes differences in the Nelson-Aalen estimate of H(t). We generally expect the hazard rate to change smoothly (if it changes) over time, rather than jump around haphazardly. To accomplish this smoothing, the hazard function estimate at any time interval is a weighted average of differences within a window of time that includes many differences, known as the bandwidth. Widening the bandwidth smooths the function by averaging more differences together. However, widening will also mask changes in the hazard function as local changes in the hazard function are drowned out by the larger number of values that are being averaged together. Below is an example of obtaining a kernel-smoothed estimate of the hazard function across BMI strata with a bandwidth of 200 days: We request plots of the hazard function with a bandwidth of 200 days with plothazard(bw200) SAS conveniently allows the creation of strata from a continuous variable, such as bmi, on the fly with the strata statement We specify the left endpoints of each bmi to form 5 bmi categories: 15-18.5, 18.5-25, 25-30, 30-40, and 40. The lines in the graph are labeled by the midpoint bmi in each group. From the plot we can see that the hazard function indeed appears higher at the beginning of follow-up time and then decreases until it levels off at around 500 days and stays low and mostly constant. The hazard function is also generally higher for the two lowest BMI categories. The sudden upticks at the end of follow-up time are not to be trusted, as they are likely due to the few number of subjects at risk at the end. The red curve representing the lowest BMI category is truncated on the right because the last person in that group died long before the end of followup time. 4. Background: The Cox proportional hazards regression model 4.1. Background: Estimating the hazard function, h(t) Whereas with non-parametric methods we are typically studying the survival function, with regression methods we examine the hazard function, h(t). The hazard function for a particular time interval gives the probability that the subject will fail in that interval, given that the subject has not failed up to that point in time. The hazard rate can also be interpreted as the rate at which failures occur at that point in time, or the rate at which risk is accumulated, an interpretation that coincides with the fact that the hazard rate is the derivative of the cumulative hazard function, H(t). In regression models for survival analysis, we attempt to estimate parameters which describe the relationship between our predictors and the hazard rate. We would like to allow parameters, the betas, to take on any value, while still preserving the non-negative nature of the hazard rate. A common way to address both issues is to parameterize the hazard function as: In this parameterization, h(tx) is constrained to be strictly positive, as the exponential function always evaluates to positive, while beta0 and beta1 are allowed to take on any value. Notice, however, that t does not appear in the formula for the hazard function, thus implying that in this parameterization, we do not model the hazard rates dependence on time. A complete description of the hazard rates relationship with time would require that the functional form of this relationship be parameterized somehow (for example, one could assume that the hazard rate has an exponential relationship with time). However, in many settings, we are much less interested in modeling the hazard rates relationship with time and are more interested in its dependence on other variables, such as experimental treatment or age. For such studies, a semi-parametric model, in which we estimate regression parameters as covariate effects but ignore (leave unspecified) the dependence on time, is appropriate. 4.2. Background: The Cox proportional hazards model We can remove the dependence of the hazard rate on time by expressing the hazard rate as a product of h0(t), a baseline hazard rate which describes the hazard rates dependence on time alone, and r(x, betax), which describes the hazard rates dependence on the other x covariates: In this parameterization, h(t) will equal h0(t) when r(x, betax) 1. It is intuitively appealing to let r(x, betax) 1 when all x 0, thus making the baseline hazard rate, h0(t), equivalent to a regression intercept. Above, we discussed that expressing the hazard rates dependence on its covariates as an exponential function conveniently allows the regression coefficients to take on any value while still constraining the hazard rate to be positive. The exponential function is also equal to 1 when its argument is equal to 0. We will thus let r(x, betax) exp(xbetax), and the hazard function will be given by: This parameterization forms the Cox proportional hazards model . It is called the proportional hazards model because the ratio of hazard rates between two groups with fixed covariates will stay constant over time in this model. For example, the hazard rate when time t when x x1 would then be h(tx1) h0(t)exp(x1betax), and at time t when x x2 would be h(tx2) h0(t)exp(x2betax). The covariate effect of x, then is the ratio between these two hazard rates, or a hazard ratio(HR): Notice that the baseline hazard rate, h0(t) is cancelled out, and that the hazard rate does not depend on time t: The hazard rate HR will thus stay constant over time with fixed covariates. Because of this parameterization, covariate effects are multiplicative rather than additive and are expressed as hazard ratios, rather than hazard differences. As we see above, one of the great advantages of the Cox model is that estimating predictor effects does not depend on making assumptions about the form of the baseline hazard function, h0(t), which can be left unspecified. Instead, we need only assume that whatever the baseline hazard function is, covariate effects multiplicatively shift the hazard function and these multiplicative shifts are constant over time. Cox models are typically fitted by maximum likelihood methods, which estimate the regression parameters that maximize the probability of observing the given set of survival times. So what is the probability of observing subject i fail at time tj At the beginning of a given time interval tj, say there are Rj subjects still at-risk, each with their own hazard rates: The probability of observing subject j fail out of all Rj remaing at-risk subjects, then, is the proportion of the sum total of hazard rates of all Rj subjects that is made up by subject js hazard rate. For example, if there were three subjects still at risk at time tj, the probability of observing subject 2 fail at time tj would be: All of those hazard rates are based on the same baseline hazard rate h0(ti), so we can simplify the above expression to: We can similarly calculate the joint probability of observing each of the n subjects failure times, or the likelihood of the failure times, as a function of the regression parameters, beta, given the subjects covariates values xj: where Rj is the set of subjects still at risk at time tj. Maximum likelihood methods attempt to find the beta values that maximize this likelihood, that is, the regression parameters that yield the maximum joint probability of observing the set of failure times with the associated set of covariate values. Because this likelihood ignores any assumptions made about the baseline hazard function, it is actually a partial likelihood, not a full likelihood, but the resulting beta have the same distributional properties as those derived from the full likelihood. 5. Cox proportional hazards regression in SAS using proc phreg 5.1. Fitting a simple Cox regression model We request Cox regression through proc phreg in SAS. Previously, we graphed the survival functions of males in females in the WHAS500 dataset and suspected that the survival experience after heart attack may be different between the two genders. Perhaps you also suspect that the hazard rate changes with age as well. Below we demonstrate a simple model in proc phreg. where we determine the effects of a categorical predictor, gender, and a continuous predictor, age on the hazard rate: To specify that gender is a categorical predictor, we enter it on the class statement. We also would like survival curves based on our model, so we add plotssurvival to the proc phreg statement, although as we shall see this specification is probably insufficient for what we want. On the model statement, on the left side of the equation, we provide the follow up time variable, lenfol, and the censoring variable, fstat, with all censoring values listed in parentheses. On the right side of the equation we list all the predictors. Model Fit Statistics The above output is only a portion of what SAS produces each time you run proc phreg. In particular we would like to highlight the following tables: Model Fit Statistics. Displays fit statistics which are typically used for model comparison and selection. This is our first model, so we have no other model to compare with, except that by default SAS will display model fit statistics of a model with no predictors. We see here that adding gender and particularly age (as we will see below) as predictors improves the fit of the model, as all three statistics decrease Testing Global Null Hypothesis: BETA0. Displays test of hypothesis that all coefficients in the model are 0, that is, an overall test of whether the model as a whole can predict changes in the hazard rate. These tests are asymptotically equivalent, but may differ in smaller samples, in which case the likelihood ratio test is generally preferred. Here the tests agree, and it appears that at least one of our regression coefficients is significantly different from 0. Analysis of Maximum Likelihood Estimates. Displays model coefficients, tests of significance, and exponentiated coefficient as hazard ratio. Here it appears that although females have a 6 (Hazard Ratio 0.937) decrease in the hazard rate compared to males, this decrease is not significant. On the other hand, with each year of age the hazard rate increases by 7 (Hazard Ratio 1.069), a significant change. Our initial supsicion that the hazard rates were different between genders seems to be wrong once we account for age effects (females are generally older in this dataset), but as shall see the effects are more nuanced. Also notice that there is no intercept. In Cox regression, the intercept is absorbed into the baseline hazard function, which is left unspecified. 5.2. Producing graphs of the survival and baseline hazard function after Cox regression Handily, proc phreg has pretty extensive graphing capabilities. plotssurvival to the proc phreg statement./p When only plotssurvival is specified on the proc phreg statement, SAS will produce one graph, a reference curve of the survival function at the reference level of all categorical predictors and at the mean of all continuous predictors. Reference Set of Covariates for Plotting In this model, this reference curve is for males at age 69.845947 Usually, we are interested in comparing survival functions between groups, so we will need to provide SAS with some additional instructions to get these graphs. 5.2.1. Use the baseline statement to generate survival plots by group Acquiring more than one curve, whether survival or hazard, after Cox regression in SAS requires use of the baseline statement in conjunction with the creation of a small dataset of covariate values at which to estimate our curves of interest. Here are the typical set of steps to obtain survival plots by group: First, a dataset of covariate values is created in a data step. Each row contains a set of covariate values for which we would like a survival plot. This dataset name is then specified on the covariates option on the baseline statement. Internally, SAS will expand the dataset to contain one observation at each event time per set of covariate values in the covariates dataset. This expanded dataset can be named and then viewed with the out option, but obtaining the out dataset is not at all necessary to generate the survival plots. Two options on the baseline statement control grouping in the graphs. If a variable is specified after group (not used until later in the seminar), SAS will create separate graphs for each level of that variable. If a variable is specified after the rowid option, SAS will create separate lines within the same plot for each level of this variable. The group and rowid options on the baseline statment work in tandem with the (overlaygroup) option specified immediately after the plots option on the proc phreg statement. If plots(overlaygroup) is specified, and there is a variable specified on the group option on the baseline statement, SAS will create separate graphs by level of that variable. If additionally a variable is specified on the rowid option on the baseline statement, SAS will plot separate lines by this variable in each plot. If no group option is used, we can still get separate lines by the rowid variable on one plot by specifying no type of overlaying like so: plots(overlay). Omitting the (overlay) completely will tell SAS to create separate graphs by rowid . Both survival and cumulative hazard curves are available using the plots option on the proc phreg statement, with the keywords survival and cumhaz. respectively. Lets get survival curves (cumulative hazard curves are also available) for males and female at the mean age of 69.845947 in the manner we just described. We use a data step to create a dataset called covs with 2 rows of covariates We then specify covs on covariates option on the baseline statement. There are 326 discrete event times in the WHAS500 dataset, so the baseline statement will then expand the covariates dataset so that we have 326 entries each for males and females at the mean age. We specify the name of the output dataset, base, that contains our covariate values at each event time on the out option We request survival plots that are overlaid with the plot(overlay)(survival) specification on the proc phreg statement. If we did not specify (overlay). SAS would produce separate graphs for males and females. We also add the rowid option on the baseline statement, which tells SAS to label the curves on our graph using the variable gender . The survival curves for females is slightly higher than the curve for males, suggesting that the survival experience is possibly slightly better (if significant) for females, after controlling for age. The estimated hazard ratio of .937 comparing females to males is not significant. 5.3. Expanding and interpreting the Cox regression model with interaction terms In our previous model we examined the effects of gender and age on the hazard rate of dying after being hospitalized for heart attack. At this stage we might be interested in expanding the model with more predictor effects. For example, we found that the gender effect seems to disappear after accounting for age, but we may suspect that the effect of age is different for each gender. We could test for different age effects with an interaction term between gender and age. Based on past research, we also hypothesize that BMI is predictive of the hazard rate, and that its effect may be non-linear. Finally, we strongly suspect that heart rate is predictive of survival, so we include this effect in the model as well. In the code below we fit a Cox regression model where we allow examine the effects of gender, age, bmi, and heart rate on the hazard rate. Here, we would like to introdue two types of interaction: The interaction of 2 different variables, such as gender and age, is specified through the syntax genderage. which requests inidividual effects of each term as well as their interaction. This allows the effect of age to differ by gender (and the effect of gender to differ by age). The interaction of a continuous variable, such as bmi, with itself is specified by bmibmi. to model both linear and quadratic effects of that variable. A quadratic effect implies that the effect of the variable changes with the level of the variable itself (i. e. an interaction of the variable with itself). Model Fit Statistics We would probably prefer this model to the simpler model with just gender and age as explanatory factors for a couple of reasons. First, each of the effects, including both interactions, are significant. Second, all three fit statistics, -2 LOG L . AIC and SBC . are each 20-30 points lower in the larger model, suggesting the including the extra parameters improve the fit of the model substantially. Lets interpret our model. We should begin by analyzing our interactions. The significant AGEGENDER interaction term suggests that the effect of age is different by gender. Recall that when we introduce interactions into our model, each individual term comprising that interaction (such as GENDER and AGE ) is no longer a main effect, but is instead the simple effect of that variable with the interacting variable held at 0. Thus, for example the AGE term describes the effect of age when gender0, or the age effect for males. It appears that for males the log hazard rate increases with each year of age by 0.07086, and this AGE effect is significant, p hazardratio statement and graphs to interpret effects, particularly interactions Notice in the Analysis of Maximum Likelihood Estimates table above that the Hazard Ratio entries for terms involved in interactions are left empty. SAS omits them to remind you that the hazard ratios corresponding to these effects depend on other variables in the model. Below, we show how to use the hazardratio statement to request that SAS estimate 3 hazard ratios at specific levels of our covariates. After the keyword hazardratio. we can optionally apply a label, then we specify the variable whose levels are to be compared in the hazard, and finally after the option keyword at we tell SAS at which level of our other covariates to evaluate this hazard ratio. If the variable whose hazard rates are to computed is not involved in an interaction, specification of additional covariates is unncessary since the hazard ratio is constant across levels of all other covariates (a main effect). We calculate the hazard ratio describing a one-unit increase in age, or frac , for both genders. Notice the ALL following gender. which is used only with class variables to request the hazard ratio at all levels of the class variable. We also calculate the hazard ratio between females and males, or frac at ages 0, 20, 40, 60, and 80. Finally, we calculate the hazard ratio describing a 5-unit increase in bmi, or frac , at clinically revelant BMI scores. Notice the additional option units5. BMI classes are typically separated by about 5 points, so we would like to see how the hazard ratio between (approximately) adjacent BMI classes changes as bmi increases. Effect of 1-unit change in age by gender: Hazard Ratios for AGE In each of the tables, we have the hazard ratio listed under Point Estimate and confidence intervals for the hazard ratio. Confidence intervals that do not include the value 1 imply that hazard ratio is significantly different from 1 (and that the log hazard rate change is significanlty different from 0). Thus, in the first table, we see that the hazard ratio for age, frac , is lower for females than for males, but both are significantly different from 1. Thus, both genders accumulate the risk for death with age, but females accumulate risk more slowly. In the second table, we see that the hazard ratio between genders, frac , decreases with age, significantly different from 1 at age 0 and age 20, but becoming non-signicant by 40. We previously saw that the gender effect was modest, and it appears that for ages 40 and up, which are the ages of patients in our dataset, the hazard rates do not differ by gender. Finally, we see that the hazard ratio describing a 5-unit increase in bmi. frac , increases with bmi. The effect of bmi is significantly lower than 1 at low bmi scores, indicating that higher bmi patients survive better when patients are very underweight, but that this advantage disappears and almost seems to reverse at higher bmi levels. Graphs are particularly useful for interpreting interactions. We can plot separate graphs for each combination of values of the covariates comprising the interactions. Below we plot survivor curves across several ages for each gender through the follwing steps: We again first create a covariates dataset, here called covs2. to tell SAS at which covariate values we would like to estimate the survivor function. Here we want curves for both males and females at ages 40, 60, and 80. All predictors in the model must be in the covariates dataset, so we set bmi and hr to their means. We then specify the name of this dataset in the covariates option on the baseline statement. We request separate lines for each age using rowid and separate graphs by gender using group on the baseline statement. We request that SAS create separate survival curves by the group option, with separate curves by rowid overlaid on the same graph with the syntax plots(overlaygroup)(survival). As we surmised earlier, the effect of age appears to be more severe in males than in females, reflected by the greater separation between curves in the top graaph. 5.5. Create time-varying covariates with programming statements Thus far in this seminar we have only dealt with covariates with values fixed across follow up time. With such data, each subject can be represented by one row of data, as each covariate only requires only value. However, often we are interested in modeling the effects of a covariate whose values may change during the course of follow up time. For example, patients in the WHAS500 dataset are in the hospital at the beginnig of follow-up time, which is defined by hospital admission after heart attack. Many, but not all, patients leave the hospital before dying, and the length of stay in the hospital is recorded in the variable los. We, as researchers, might be interested in exploring the effects of being hospitalized on the hazard rate. As we know, each subject in the WHAS500 dataset is represented by one row of data, so the dataset is not ready for modeling time-varying covariates. Our goal is to transform the data from its original state: Notice the creation of start and stop variables, which denote the beginning and end intervals defined by hospitalization and death (or censoring). Notice also that care must be used in altering the censoring variable to accommodate the multiple rows per subject. If the data come prepared with one row of data per subject each time a covariate changes value, then the researcher does not need to expand the data any further. However, if that is not the case, then it may be possible to use programming statement within proc phreg to create variables that reflect the changing the status of a covariate. Alternatively, the data can be expanded in a data step, but this can be tedious and prone to errors (although instructive, on the other hand). Fortunately, it is very simple to create a time-varying covariate using programming statements in proc phreg. These statement essentially look like data step statements, and function in the same way. In the code below, we model the effects of hospitalization on the hazard rate. To do so: We create the variable inhosp. which is 1 if the patient is currently in the hospital ( lenfol los ), and 0 when the patient leaves ( lenfol los ). We also add the newly created time-varying covariate to the model statement. Analysis of Maximum Likelihood Estimates GENDER Female AGE It appears that being in the hospital increases the hazard rate, but this is probably due to the fact that all patients were in the hospital immediately after heart attack, when they presumbly are most vulnerable. 6. Exploring functional form of covariates In the Cox proportional hazards model, additive changes in the covariates are assumed to have constant multiplicative effects on the hazard rate (expressed as the hazard ratio (HR)): In other words, each unit change in the covariate, no matter at what level of the covariate, is associated with the same percent change in the hazard rate, or a constant hazard ratio. For example, if betax is 0.5, each unit increase in x will cause a 65 increase in the hazard rate, whether X is increasing from 0 to 1 or from 99 to 100, as HR exp(0.5(1)) 1.6487. However, it is quite possible that the hazard rate and the covariates do not have such a loglinear relationship. Constant multiplicative changes in the hazard rate may instead be associated with constant multiplicative, rather than additive, changes in the covariate, and might follow this relationship: HR exp(betax(log(x2)-log(x1)) exp(betax(logfrac )) This relationship would imply that moving from 1 to 2 on the covariate would cause the same percent change in the hazard rate as moving from 50 to 100. It is not always possible to know a priori the correct functional form that describes the relationship between a covariate and the hazard rate. Plots of the covariate versus martingale residuals can help us get an idea of what the functional from might be. 6.1 Plotting cumulative martingale residuals against covariates to determine the functional form of covariates The background necessary to explain the mathematical definition of a martingale residual is beyond the scope of this seminar, but interested readers may consult (Therneau, 1990). For this seminar, it is enough to know that the martingale residual can be interpreted as a measure of excess observed events . or the difference between the observed number of events and the expected number of events under the model: Therneau and colleagues(1990) show that the smooth of a scatter plot of the martingale residuals from a null model (no covariates at all) versus each covariate individually will often approximate the correct functional form of a covariate. Previously we suspected that the effect of bmi on the log hazard rate may not be purely linear, so it would be wise to investigate further. In the code below we demonstrate the steps to take to explore the functional form of a covariate: Run a null Cox regression model by leaving the right side of equation empty on the model statement within proc phreg . Save the martingale residuals to an output dataset using the resmart option in the output statement within proc phreg. In the code below we save the residuals to a variable named martingale. Use proc loess to plot scatter plot smooths of the covariate (here bmi) vs the martingale residuals. The loess method selects portions of the data into local neighborhoods and fits a regression surface to each neighboorhood. This allows the regression surface to take a wide variety of shapes. The smoothed regression surfaces should approximate the functional form of the covariate. Within proc loess we specify the martingale residual dataset on the proc loess statement. We specify which variables to model on the model statement. The fraction of the data contained in each neighborhood is determined by the smoothing parameter, and thus larger smoothing parameter values produce smoother surfaces. Below we request 4 smooths using the smooth option. A desirable feature of loess smooth is that the residuals from the regression do not have any structure. We can examine residual plots for each smooth (with loess smooth themselves) by specifying the plotsResidualsBySmooth option on the proc loess statement. In the left panel above, Fits with Specified Smooths for martingale, we see our 4 scatter plot smooths. In all of the plots, the martingale residuals tend to be larger and more positive at low bmi values, and smaller and more negative at high bmi values. This indicates that omitting bmi from the model causes those with low bmi values to modeled with too low a hazard rate (as the number of observed events is in excess of the expected number of events). On the right panel, Residuals at Specified Smooths for martingale, are the smoothed residual plots, all of which appear to have no structure. The surface where the smoothing parameter0.2 appears to be overfit and jagged, and such a shape would be difficult to model. However, each of the other 3 at the higher smoothing parameter values have very similar shapes, which appears to be a linear effect of bmi that flattens as bmi increases. This indicates that our choice of modeling a linear and quadratic effect of bmi was a reasonable one. One caveat is that this method for determining functional form is less reliable when covariates are correlated. However, despite our knowledge that bmi is correlated with age, this method provides good insight into bmis functional form. 6.2. Using the assess statement to explore functional forms SAS provides built-in methods for evaluating the functional form of covariates through its assess statement. These techniques were developed by Lin, Wei and Zing (1993). The basic idea is that martingale residuals can be grouped cumulatively either by follow up time and/or by covariate value. If our Cox model is correctly specified, these cumulative martingale sums should randomly fluctuate around 0. Significant departures from random error would suggest model misspecification. We could thus evaluate model specification by comparing the observed distribution of cumulative sums of martingale residuals to the expected distribution of the residuals under the null hypothesis that the model is correctly specified. The null distribution of the cumulative martingale residuals can be simulated through zero-mean Gaussian processes. If the observed pattern differs significantly from the simulated patterns, we reject the null hypothesis that the model is correctly specified, and conclude that the model should be modified. In such cases, the correct form may be inferred from the plot of the observed pattern. This technique can detect many departures from the true model, such as incorrect functional forms of covariates (discussed in this section), violations of the proportional hazards assumption (discussed later), and using the wrong link function (not discussed). Below we demonstrate use of the assess statement to the functional form of the covariates. Several covariates can be evaluated simultaneously. We compare 2 models, one with just a linear effect of bmi and one with both a linear and quadratic effect of bmi (in addition to our other covariates). Using the assess statement to check functional form is very simple: List all covariates whose functional forms are to be checked within parentheses after var on the assess statement. Only continuous covariates may be assessed this way, not class variables. We also specify the resample option, which performs a supremum test of the null hypothesis that the observed pattern of martingale residuals is not different from the expected pattern (i. e. that the model is correctly specified). Essentially, the supremum tests calculates the proportion of 1000 simulations that contain a maximum cumulative martingale residual larger than the observed maximum cumulative residual. This proportion is reported as the p-value. If only a small proportion, say 0.05, of the simulations have a maximum cumulative residual larger than the observed maximum, then that suggests that the observed residuals are larger than expected under the proposed model and that the model should be modified. First lets look at the model with just a linear effect for bmi. In each of the graphs above, a covariate is plotted against cumulative martingale residuals. The solid lines represent the observed cumulative residuals, while dotted lines represent 20 simulated sets of residuals expected under the null hypothesis that the model is correctly specified. Unless the seed option is specified, these sets will be different each time proc phreg is run. A solid line that falls significantly outside the boundaries set up collectively by the dotted lines suggest that our model residuals do not conform to the expected residuals under our model. None of the graphs look particularly alarming (click here to see an alarming graph in the SAS example on assess ). Additionally, none of the supremum tests are significant, suggesting that our residuals are not larger than expected. Nevertheless, the bmi graph at the top right above does not look particularly random, as again we have large positive residuals at low bmi values and smaller negative residuals at higher bmi values. This suggests that perhaps the functional form of bmi should be modified. Now lets look at the model with just both linear and quadratic effects for bmi. Supremum Test for Functional Form Pr gt MaxAbsVal The graph for bmi at top right looks better behaved now with smaller residuals at the lower end of bmi. The other covariates, including the additional graph for the quadratic effect for bmi all look reasonable. Thus, we again feel justified in our choice of modeling a quadratic effect of bmi. 7. Assessing the proportional hazards assumption A central assumption of Cox regression is that covariate effects on the hazard rate, namely hazard ratios, are constant over time. For example, if males have twice the hazard rate of females 1 day after followup, the Cox model assumes that males have twice the hazard rate at 1000 days after follow up as well. Violations of the proportional hazard assumption may cause bias in the estimated coefficients as well as incorrect inference regarding significance of effects. 7.1. Graphing Kaplan-Meier survival function estimates to assess proportional hazards for categorical covariates In the case of categorical covariates, graphs of the Kaplan-Meier estimates of the survival function provide quick and easy checks of proportional hazards. If proportional hazards holds, the graphs of the survival function should look parallel, in the sense that they should have basically the same shape, should not cross, and should start close and then diverge slowly through follow up time. Earlier in the seminar we graphed the Kaplan-Meier survivor function estimates for males and females, and gender appears to adhere to the proportional hazards assumption. 7.2. Plotting scaled Schoenfeld residuals vs functions of time to assess proportional hazards of a continuous covariate A popular method for evaluating the proportional hazards assumption is to examine the Schoenfeld residuals. The Schoenfeld residual for observation j and covariate p is defined as the difference between covariate p for observation j and the weighted average of the covariate values for all subjects still at risk when observation j experiences the event. Grambsch and Therneau (1994) show that a scaled version of the Schoenfeld residual at time k for a particular covariate p will approximate the change in the regression coefficient at time k: E(sstar ) hat p approx betaj(tk) In the relation above, sstar is the scaled Schoenfeld residual for covariate p at time k, betap is the time-invariant coefficient, and betaj(tk) is the time-variant coefficient. In other words, the average of the Schoenfeld residuals for coefficient p at time k estimates the change in the coefficient at time k. Thus, if the average is 0 across time, then that suggests the coefficient p does not vary over time and that the proportional hazards assumption holds for covariate p. It is possible that the relationship with time is not linear, so we should check other functional forms of time, such as log(time) and rank(time). We will use scatterplot smooths to explore the scaled Schoenfeld residuals relationship with time, as we did to check functional forms before. Here are the steps we will take to evaluate the proportional hazards assumption for age through scaled Schoenfeld residuals: Scaled Schoenfeld residuals are obtained in the output dataset, so we will need to supply the name of an output dataset using the out option on the output statement as before. Below, we call this dataset schoen. SAS provides Schoenfeld residuals for each covariate, and they are output in the same order as the coefficients are listed in the Analysis of Maximum Likelihood Estimates table. Only as many residuals are output as names are supplied on the ressch option. For this demonstration, we are particularly interested in the Schoenfeld residuals for age. We should check for non-linear relationships with time, so we include a data step that calculates the log of lenfol. Other functions can be explored as well. We then use proc loess to obtain our smooths. Flat lines at 0 suggest that the coefficient does not vary over time and that proportional hazards holds. Although possibly slightly positively trending, the smooths appear mostly flat at 0, suggesting that the coefficient for age does not change over time and that proportional hazards holds for this covariate. The same procedure could be repeated to check all covariates. 7.3. Using assess with the ph option to check proportional hazards The procedure Lin, Wei, and Zing(1990) developed that we previously introduced to explore covariate functional forms can also detect violations of proportional hazards by using a transform of the martingale residuals known as the empirical score process. Once again, the empirical score process under the null hypothesis of no model misspecification can be approximated by zero mean Gaussian processes, and the observed score process can be compared to the simulated processes to asses departure from proportional hazards. The assess statement with the ph option provides an easy method to assess the proportional hazards assumption both graphically and numerically for many covariates at once. Here we demonstrate how to assess the proportional hazards assumption for all of our covariates (graph for gender not shown): As before with checking functional forms, we list all the variables for which we would like to assess the proportional hazards assumption after the var option on the assess statement. We additionally add the option ph to tell SAS that we would like to assess proportional hazards in addition to checking functional forms. As before, we specify the resample option to request the supremum tests of the null hypothesis that proportional hazards holds. These tests calculate the proportion of simulated score processes that yielded a maximum score larger than the maximum observed score process. A very small proportion (p-value) suggests violation of proportional hazards. Supremum Test for Proportionals Hazards Assumption As we did with functional form checking, we inspect each graph for observed score processes, the solid blue lines, that appear quite different from the 20 simulated score processes, the dotted lines. None of the solid blue lines looks particularly aberrant, and all of the supremum tests are non-significant, so we conclude that proportional hazards holds for all of our covariates. 7.4. Dealing with nonproportionality If nonproportional hazards are detected, the researcher has many options with how to address the violation (Therneau Grambsch, 2000): Ignore the nonproportionality if it appears the changes in the coefficient over time are very small or if it appears the outliers are driving the changes in the coefficient. In large datasets, very small departures from proportional hazards can be detected. If, say, a regression coefficient changes only by 1 over time, it is unlikely that any overarching conclusions of the study would be affected. Additionally, a few heavily influential points may be causing nonproportional hazards to be detected, so it is important to use graphical methods to ensure this is not the case. Stratify the model by the nonproportional covariate. Stratification allows each stratum to have its own baseline hazard, which solves the problem of nonproportionality. However, one cannot test whether the stratifying variable itself affects the hazard rate significantly. Additionally, although stratifying by a categorical covariate works naturally, it is often difficult to know how to best discretize a continuous covariate. This can be easily accomplished in proc phreh with the strata statement. Run Cox models on intervals of follow up time rather than on its entirety. Proportional hazards may hold for shorter intervals of time within the entirety of follow up time. Some data management will be required to ensure that everyone is properly censored in each interval. Include covariate interactions with time as predictors in the Cox model. This can be accomplished through programming statements in proc phreg. as these interactions are time-varying covariates themselves. Indeed, including such an interaction has been used as a test of proportional hazards -- a significant interaction indicates violation of the assumption. Below, we provide code that shows how to include a covariate interaction with time in the model. We create the interaction variable hrtime by multiplying hr by lenfol. The interaction variable is of course included on the model statement as well. The output indicates that this interaction is non-significant, which is not surprising given that hr has not shown evidence of nonproportionality. Analysis of Maximum Likelihood Estimates 8. Influence Diagnostics 8.1. Inspecting dfbetas to assess influence of observations on individual regression coefficients After fitting a model it is good practice to assess the influence of observations in your data, to check if any outlier has a disproportionately large impact on the model. Once outliers are identified, we then decide whether to keep the observation or throw it out, because perhaps the data may have been entered in error or the observation is not particularly representative of the population of interest. The dfbeta measure quantifies how much an observation influences the regression coefficients in the model. For observation j, dfbetaj approximates the change in a coefficient when that observation is deleted. We thus calculate the coefficient with the observation, call it beta, and then the coefficient when observation j is deleted, call it betaj, and take the difference to obtain dfbetaj. Positive values of dfbetaj indicate that the exclusion of the observation causes the coefficient to decrease, which implies that inclusion of the observation causes the coefficient to increase. Thus, it might be easier to think of dfbetaj as the effect of including observation j on the the coefficient. SAS provides easy ways to examine the dfbeta values for all observations across all coefficients in the model. Plots of covariates vs dfbetas can help to identify influential outliers. Here are the steps we use to assess the influence of each observation on our regression coefficients: We obtain dfbeta values through in output datasets in SAS, so we will need to specify an output statement within proc phreg. On the output statement, we supply the name of the output dataset dfbeta on the out option. There are dfbeta values associated with each coefficient in the model, and they are output to the output dataset in the order that they appear in the parameter table Analysis of Maximum Likelihood Estimates (see above). The order of dfbetas in the current model are: gender, age, genderage, bmi, bmibmi, hr. SAS expects individual names for each dfbeta associated with a coefficient. If only k names are supplied and k is less than the number of distinct dfbetas, SAS will only output the first k dfbetas. Thus, to pull out all 6 dfbetas, we must supply 6 variable names for these dfbetas. We then plot each dfbeta against the associated coviarate using proc sgplot. Our aim is identifying which observations are influential, so we replace the marker symbol with the id number of the observation by specifying the variable id on the markerchar option. The dfbetas for age and hr look small compared to regression coefficients themselves (hat 0.07086 and hat 0.01277) for the most part, but id89 has a rather large, negative dfbeta for hr. We also identify id89 again and id112 as influential on the linear bmi coefficient (hat -0.23323), and their large positive dfbetas suggest they are pulling up the coefficient for bmi when they are included. Once you have identified the outliers, it is good practice to check that their data were not incorrectly entered. These two observations, id89 and id112, have very low but not unreasonable bmi scores, 15.9 and 14.8. However they lived much longer than expected when considering their bmi scores and age (95 and 87), which attenuates the effects of very low bmi. Thus, we can expect the coefficient for bmi to be more severe or more negative if we exclude these observations from the model. Indeed, exclusion of these two outliers causes an almost doubling of hat , from -0.23323 to -0.39619. Still, although their effects are strong, we believe the data for these outliers are not in error and the significance of all effects are unaffected if we exclude them, so we include them in the model. 8.2. Plotting likelihood displacement scores to assess influence on the overall model Not only are we interested in how influential observations affect coefficients, we are interested in how they affect the model as a whole. The likelihood displacement score quantifies how much the likelihood of the model, which is affected by all coefficients, changes when the observation is left out. This analysis proceeds in much the same was as dfbeta analysis, in that we will: Output the likelihood displacement scores to an output dataset, which we name on the out option on the output statement in proc phreg. Below, we name the output dataset ld. Name the variable to store the likelihood displacement score on the ld option on the output statement Graph the likelihood displacement scores vs follow up time using proc sgplot. We replace the marker symbols with the id number using the markerchar option again. We see the same 2 outliers we identifed before, id89 and id112, as having the largest influence on the model overall, probably primarily through their effects on the bmi coefficient. However, we have decided that there covariate scores are reasonable so we retain them in the model. References Therneau, TM, Grambsch, PM. (2000). Modeling Survival Data: Extending the Cox Model. Springer: New York. Note: This was the primary reference used for this seminar. It contains numerous examples in SAS and R. Grambsch, PM, Therneau, TM. (1994). Proportional hazards tests and diagnostics based on weighted residuals. Biometrika . 81. 515-526. Grambsch, PM, Therneau, TM, Fleming TR. (1995). Diagnostic plots to reveal functional form for covariates in multiplicative intensity models. Biometrics . 51. 1469-82. Hosmer, DW, Lemeshow, S, May S. (2008). Applied Survival Analysis. Wiley: Hoboken. Lin, DY, Wei, LJ, Ying, Z. (1993). Checking the Cox model with cumulative sums of martingale-based residuals. Biometrika . 80(30). 557-72. Therneau, TM, Grambsch PM, Fleming TR (1990). Martingale-based residuals for survival models. Biometrika . 77(1). 147-60. O conteúdo deste site não deve ser interpretado como um endosso de qualquer site, livro ou produto de software específico pela Universidade da Califórnia.

No comments:

Post a Comment