понедельник, 14 мая 2018 г.

Número máximo de regressores no stata forex


Análise de fundos de hedge - Modelos Excel Modelos VBA e Modelos Financeiros lsquoIt é um bom exercício matutino para um cientista de pesquisa descartar uma hipótese de animal de estimação todos os dias antes do café da manhã mantém youngrsquo Nesta página você pode encontrar uma seleção de modelos estatísticos, modelos VBA e Excel modelos financeiros baseados em Todas as planilhas e applets estão disponíveis para download. Alguns modelos não são de código aberto, mas as senhas para acessar os módulos no editor do Visual Basic podem ser obtidas através da página de contato. Por favor, sinta-se livre para comentar sobre suas experiências e sugerir melhorias nos modelos. Observe que alguns modelos ainda estão em um estágio de desenvolvimento (verifique o status) o autor não se responsabiliza por quaisquer falhas ou erros no código-fonte. Bookmark este site para verificar atualizações e novos desenvolvimentos regularmente. Por favor, note que no Windows 7 arquivos só podem ser baixados como. zip. Basta abrir o arquivo compactado no Excel e salvar como pasta de trabalho para uso posterior. downloads: 7181 type: xlsm size: 189 kB Última atualização: abril de 2010. As seguintes alterações foram implementadas: Um novo algoritmo foi introduzido para calcular as matrizes inversas com mais precisão através do algoritmo de Gauss-Jordan. A fórmula pode ser usada para exibir os resíduos de regressão. Estimação de Mínimos Quadrados sem constante (intercepção na origem) e rótulos de dados. Versão estendida do Errorhandler. O modelo acima usa a álgebra matricial para determinar coeficientes de regressão, previsões e intervalos de confiança. Assim, a função REGOUTPUT () não está sujeita às limitações do Linest () - Função / Matriz-Funções inerentes ao Excel. Além disso, o modelo fornece diagnósticos de regressão extensivos: teste para colinearidade de termos de erro consecutivos, normalidade e qualidade de ajuste. downloads: 3309 type: xlsm size: 211 kB Este modelo usa um algoritmo de regressão forward stepwise para selecionar variáveis ​​preditoras a partir de um intervalo de parâmetros. Os parâmetros de entrada incluem o nível de tolerância, F-to-leave e F-to-enter. O número máximo de iterações é definido como 1000, mas pode ser alterado manualmente no código-fonte (por favor, pergunte primeiro sobre a senha). Os parâmetros de saída são idênticos ao modelo de regressão de múltiplos fatores. downloads: 3785 tipo: xlsm tamanho: 229 kB Este modelo permite diferentes cálculos de estimativas de erro padrão de coeficiente na regressão de séries temporais: Estimativa OLS padrão assumindo variância constante. Estimativa de erro padrão branco. Erros padrão de GMM e estimativa de Newey-West (ponderada de acordo com o núcleo de Bartlett). O truncamento de retardo para estimativas de Newey-West pode ser especificado separadamente. downloads: 2967 type: xlsm size: 67 kB De acordo com os modelos Sharpe Multifactor Pricing, a rotina acima calcula os coeficientes estimados para um número de regressores com base no pressuposto de que a soma dos coeficientes 1. Isso permite uma interpretação mais significativa de as cargas fatoriais. A planilha usa um exemplo que estima o desempenho de um fundo de hedge a partir de cinco parâmetros de entrada. downloads: 2682 tipo: xlsm size: 192 kB Esta planilha calcula o statictic de teste Durbin-Watson para correlação serial com base em um modelo de regressão de fator único. Além disso, ele retorna os limites críticos inferior e superior das tabelas Durbin-Watson (para até n 200 observações e k 20 regressores). Por favor, consulte os modelos multifator acima ao testar correlações seriadas em resíduos com k gt 2 (mais de um regressor). downloads: 2591 tipo: xlsm tamanho: 109 kB A série de dados pode ser testada quanto à normalidade usando o teste qui-quadrado não-paramétrico para a normalidade ou a estatística Jarque-Bera. Este último usa o terceiro e quarto momento da distribuição (também conhecido como inclinação e curtose). Algumas séries são consideradas mais sensíveis a uma ou outra estatística de teste. downloads: 3515 type: xlsm size: 31 kB Esta planilha fornece macros para calcular uma série de medidas de risco downside incluindo drawdown contínuo máximo, semi-deviation e Value-at-Risk. Alguns dos trechos de código foram baixados de andreassteiner. net e alterados para expressar os retornos do subperíodo como (1 R t, t 1) para considerar os efeitos de composição, onde R t, t 1 é o retorno de perentagem entre t e tempo t 1. downloads: tipo 1828: tamanho xlsm: 31 kB Este algoritmo simples compara duas séries temporais com base no teste t para médias iguais. As opções de entrada para os projetos experimentais são: emparelhadas vs aleatórias e uma cauda versus duas caudas. O teste para a igualdade de variâncias da amostra é realizado por meio do teste F. Todos os modelos são baseados em função. downloads: 3000 tipo: xlsm size: 272 kB A macro calcula os coeficientes de autocorrelação e os coeficientes parciais de autocorrelação da ordem k de qualquer série temporal. Além disso, utiliza o teste Breusch-Godfrey LM para detectar a autocorrelação em lags distintos. O teste de Durbin-Watson e o teste de Durbin h para modelos ARMA podem ser usados ​​para identificar a correlação serial entre os resíduos consecutivos na regressão linear. Todos os testes baseados em função. downloads: 3368 tipo: xlsm tamanho: 258 kB O teste de raiz unitária é conduzido como um teste aumentado de Dickey Fuller. O teste é responsável pelas primeiras diferenças (a extensão do modelo segue em breve), interceptação e atrasos apropriados. O valor p é calculado a partir de tabelas Dickey Fuller de valores críticos incluídos na macro e aproximados via interpolação linear. A estatística é baseada em funções. downloads: 3494 type: xlsm size: 328 kB Permite vários testes de raiz unitária, incluindo Dickey-Fuller, Augmented-Dickey-Fuller (ADF) e Phillips-Perron (PP). A última estatística de teste usa o estimador de variância de erro de heterocedasticidade-autocorrelação-consistente (HAC) de Newey e West (com o núcleo de Bartlett). As seguintes especificações podem ser feitas com relação à regressão de teste: diferenças consideradas, interceptação e linha de tendência incluídas, defasagens consideradas e tipo de estimativa de erro. A significância dos processos ARp é determinada de acordo com o Critério de Informação de Akaike (AIC). O número máximo de atrasos segue de Schwartz (se não especificado de outra forma). A planilha também inclui os valores críticos do McKinnon para os testes do ADF e também para o Engle-Granger. Você pode usar o CommandButton na planilha quotAR (1) - Processamento para gerar processos AR1. downloads: 2270 tipo: xlsm size: 117 kB Este script VBA usa o Monte Carlo para simular valores críticos para a estatística de teste Dickey Fuller de muitas replicações de caminhadas aleatórias (com ou sem interceptação / tendência). O usuário pode especificar o tamanho da amostra, o nível de confiança e o número de replicações. Um trecho das tabelas DF originais é incluído para comparação. downloads: 1873 tipo: xlsm tamanho: 273 kB As seguintes alterações foram feitas em março de 2010: Erros ocorridos com problemas de ANOVA não balanceados onde o número de tratamentos é maior que 6 (por exemplo, n k gt 6) foram abordados. O modelo agora funciona para qualquer número possível de níveis dos fatores A e B. Algumas mensagens de erro adicionais foram introduzidas em relação a modelos mal especificados que violam os requisitos de regressão dos modelos SS Tipo III (número mínimo de repetições necessárias para um número especificado de tratamentos ). Dois exemplos adicionais de amostra grande foram incluídos, mostrando como os pivotantes podem ser usados ​​em conjunto com as funções ANOVA. Tratamento () - funcionalidade (em vez de pivotables) para converter dados brutos em tabelas que podem ser usadas em conjunto com ANOVA. Essa macro permite que os usuários conduzam os seguintes testes de análise de variância: ANOVA de fator único, experimento de blocos aleatórios, ANOVA de fator único desequilibrado, ANOVA de dois fatores, ANOVA de dois fatores desequilibrados. Os experimentos desbalanceados requerem uma rotina simples de regressão multivariada (incluída) para comparar modelos parciais e completos. Note que pode-se usar a ANOVA para mais de dois fatores. Esta abordagem pode ser indesejável devido aos esforços computacionais envolvidos. downloads: 1795 type: xlsm size: 242 kB Esta planilha inclui três testes distintos para verificar a presença de heterocedasticidade nos termos de erro dos modelos de regressão. Para modelos univariados, a estatística de teste de Szroeter ou o teste de Breusch-Pagan podem ser usados. Para modelos multivariados, o teste de Breusch-Pagan ou, alternativamente, para modelos estendidos, diferentes testes de White podem ser aplicáveis. Como alternativa, são fornecidas soluções manuais usando funções inerentes ao Excel. downloads: 2192 type: xlsm size: 35 kB Esses algoritmos simples para avaliação de opções contornam os tediosos cálculos manuais do modelo Black-Scholes-Merton. As funções fazem provisões para taxa de juros externa / vazamento de dividendos e permitem o cálculo de todas as sensibilidades de opções relevantes (Delta, Theta, Gamma, Vega, Rho). Alternativamente, os preços das opções de lookback flutuante podem ser determinados. Todas as opções assumidas como estilo europeu (exercício apenas na data de expiração). downloads: 1558 tipo: xlsm tamanho: 192 kB A planilha dá um exemplo quanto ao uso de regressão linear múltipla na determinação da significância dos fatores e sua interação quando os tamanhos das amostras / tratamentos são desiguais em tamanho. Para uma implementação do VBA, consulte o modelo ANOVA acima. Esta pasta de trabalho inclui um modelo de planejamento financeiro que pode ser usado para analisar o ROI esperado de um empreendimento comercial. Inclui balanços, fluxo de caixa e demonstrações de resultados previstos, bem como análise de sensibilidade. Este applet é extremamente útil na elaboração de planos de negócios ou na avaliação de oportunidades de investimento. downloads: 3181 tipo: xlsm size: 93 kB Esta planilha requer o Suplemento Solver, que pode ser baixado da página inicial do Frontline Systems. Ele inclui um exemplo para construir portfólios de Variância Mínima de cinco ativos, bem como um exemplo de otimização de múltiplos objetivos (portfólios ótimos de risco-retorno) usando desvios percentuais e análise de sensibilidade. O assistente de sensibilidade também pode ser baixado da Frontline Systems. Por favor, note que o Solver não é gratuito. Um algoritmo de otimização baseado em VBA está atualmente em desenvolvimento. downloads: 3428 type: xlsm size: 3 MB Essas planilhas comparam portfólios eficientes de hedge funds e índices de ativos padrão. É útil para encontrar a alocação ideal de ativos em relação a investimentos padrão e alternativos. A planilha requer um uplink da Bloomberg para atualização de dados. downloads: 2083 tipo: xlsm tamanho: 209 kB Esta planilha mostra a relação entre estimadores de máxima verossimilhança (ML) de regressão e mínimos quadrados ordinários (OLS), assim como o cálculo de um estimador não-viesado da variabilidade em Y do ML estimador de variância. Além disso, mostra a determinação e aplicação da transformação de potência Box-Cox em Y para garantir as suposições do Modelo Linear. Para resolver as estimativas de ML, o Solver-Addin é necessário. Embora essa planilha não dependa de Macros VB, as regressões são calculadas usando a função REGOUTPUT () definida pelo usuário. Por favor habilite macros ou mude a fórmula para PROJ. LIN (). downloads: 2033 type: xlsm size: 78 kB Este modelo cria uma série ponderada de várias séries individuais. Os parâmetros de entrada são a matriz de retorno, a matriz de ponderação e um intervalo de rebalanceamento dependendo da natureza dos dados de origem (por exemplo, diariamente, trimestralmente, anual). A pasta de trabalho contém uma solução manual, bem como uma fórmula de matriz baseada em VBA. Observe que as observações de retorno ausentes devem ser inseridas como células vazias, não 0. Os pesos do portfólio podem mudar dinamicamente ao longo do tempo (matriz) ou permanecer fixo (linha única). Exemplo de regressão, parte 1: análise descritiva Qualquer análise de regressão de análise estatística, para esse assunto) deve começar com uma análise cuidadosa da matéria-prima: os dados. De onde veio, como foi medido, se está limpo ou sujo, quantas observações estão disponíveis, quais são as unidades, quais são as magnitudes e intervalos típicos dos valores e, muito importante, como são as variáveis. Muito do seu cérebro é dedicado ao processamento de informação visual, e a incapacidade de envolver essa parte do seu cérebro é como fotografar no escuro. A análise visual ajuda você a identificar padrões sistemáticos, bem como eventos incomuns e erros de dados. O objetivo desta análise será explicar e prever como a quantidade de vendas semanais de uma marca popular de cerveja depende de seu preço em uma pequena rede de supermercados. O arquivo de dados contém 52 semanas de registros de preço médio e total de vendas para três tamanhos diferentes de caixas: 12 pacotes, 18 pacotes e 30 pacotes. (Estes são dados reais, além de alguns ajustes muito pequenos para os pacotes de 30.) 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ê verá as 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, esses números devem ser redimensionados de uma forma que os torne fáceis de ler e fáceis de interpretar e comparar. Nesta análise, as variáveis ​​de preço e vendas já foram convertidas para uma base por caso (isto é, por 24 possíveis). assim, os volumes de vendas relativos para diferentes tamanhos de caixas são diretamente comparáveis ​​e, portanto, os coeficientes de regressão são diretamente comparáveis ​​para modelos ajustados a dados para diferentes tamanhos de caixas. As primeiras linhas do conjunto de dados (em um arquivo do Excel) são assim: Os títulos 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 nessa semana (ou seja, o preço de um único pacote de 12 foi 9,99) e o valor de 223,5 para CASES12PK significa que 447 12- pacotes foram vendidos (porque um caso é de 12 pacotes). Let8217s começam com um olhar para a estatística descritiva, que mostra magnitudes típicas e os intervalos das variáveis: Aqui é visto que o volume de vendas (medido em unidades comparáveis ​​de casos) foi maior para os tamanhos menores de papelão (399 casos8217 no valor de 12- embalagens versus 165 para 30 pacotes, com 18 pacotes no meio), enquanto o preço médio por caixa foi significativamente menor para os tamanhos maiores de papelão (14,38 por caixa, em média, para 30 pacotes, contra 19,09 por caso para 12 pacotes, com 18 pacotes novamente no meio). No entanto, houve variação considerável nos preços de cada tamanho de caixa, conforme mostrado pelos valores mínimo e máximo. Como essas são variáveis ​​de séries temporais, é de vital importância examinar seus gráficos de séries temporais. como mostrado abaixo. (Na verdade, você deve examinar os gráficos de suas variáveis ​​versus número de linhas, mesmo que não sejam séries temporais. Você não deseja desenhar linhas de conexão entre os pontos, para dados de séries não temporais. O que se destaca claramente nestes gráficos é que (como os compradores de cerveja atestam) os preços dos diferentes tamanhos de cartão são manipulados sistematicamente de semana para semana em uma ampla gama, e há picos nas 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 aumento correspondente nas vendas nessas duas semanas. Na verdade, se você observar todos os gráficos vendidos por casos, poderá ver que o volume de vendas para cada tamanho de caixa é bastante baixo, a menos que seu preço seja cortado em uma determinada semana. (Bebedores de cerveja de alto volume são muito sensíveis ao preço.) Outra coisa que se destaca é que o padrão de manipulação de preços não era o mesmo para todos os tamanhos de caixas. os preços das embalagens de 12 unidades não foram manipulados com muita frequência, enquanto os preços de embalagens de 30 foram manipulados quase uma vez por semana no primeiro semestre do ano, e os preços de embalagens de 18 foram manipulados com mais frequência no segundo semestre. Do ano. Então, neste ponto, temos uma boa ideia de quais são os padrões qualitativos nos preços e vendas semanais. Se nosso objetivo é medir as relações preço-demanda por meio de modelos de regressão, também estamos muito interessados ​​nas correlações entre as variáveis ​​e na aparência de seus gráficos de dispersão. Aqui está a matriz de correlação, ou seja, a tabela de todas as correlações entre pares 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 eles, numa escala de -1 a 1.) O que se destaca claramente aqui é que (como já sabíamos ao olhar o tempo gráficos de série) há correlações negativas muito fortes entre preço e vendas para todos os três tamanhos de papelão (superior a 0,8 em magnitude, como se vê), que são medidas de 8220a elasticidade-preço da demanda.8221 Há também algumas correlações positivas mais fracas entre o preço de um tamanho de caixa e as vendas de outro - por exemplo, uma correlação de 0,521 entre o preço de 18 pacotes e as vendas de 30 pacotes. Estas são medidas de elasticidades do preço cruzado8221, ou seja, efeitos de substituição. Os consumidores tendem a comprar menos 30 pacotes quando o preço de 18 pacotes é reduzido, presumivelmente porque eles compram 18 pacotes em vez disso. Por último, mas não menos importante, devemos olhar para a matriz de dispersão das variáveis, ou seja, a matriz de todos os gráficos de dispersão bidirecionais. A matriz do gráfico de dispersão é a contrapartida visual da matriz de correlação, e deve sempre ser estudada como um prelúdio para a análise de regressão se houver muitas variáveis. (Praticamente todo software de regressão comercial oferece 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 correlação, e cada gráfico separado pode ser editado.) A matriz de dispersão completa para essas variáveis ​​é uma matriz 6x6, mas estamos especialmente interessados ​​na submatriz 3x3 de gráficos de dispersão nos quais o volume de vendas é representado em relação ao preço para diferentes combinações de tamanhos de caixas: Cada uma dessas parcelas mostra não apenas a relação preço-demanda para vendas de um tamanho de embalagem versus 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 seguintes, modelos de regressão serão ajustados aos dados de vendas para pacotes de 18. A partir do gráfico de dispersão no centro da matriz, já sabemos muito sobre os resultados que obteremos se regredirmos as vendas de 18 pacotes no preço de 18 pacotes. Algumas bandeiras vermelhas8221 já estão acenando neste ponto, no entanto. As relações preço-demanda são bastante fortes, mas a variação das vendas não é consistente em toda a faixa de preços em qualquer um desses gráficos. A propósito, toda a saída mostrada acima foi gerada de uma só vez em uma única planilha do Excel com alguns pressionamentos de tecla usando o procedimento de Análise de Dados em RegressIt, como mostrado abaixo. Espero que o seu software torne isso relativamente fácil também. Bem-vindo ao Instituto de Pesquisa e Educação Digital SAS Seminário Introdução à Análise de Sobrevivência no SAS 1. Introdução A análise de sobrevivência modela os fatores que influenciam o tempo para um evento. Métodos de regressão de mínimos quadrados ordinários ficam aquém porque o tempo para o evento normalmente não é normalmente distribuído, e o modelo não pode manipular a censura, muito comum em dados de sobrevivência, sem modificação. Métodos não-paramétricos fornecem uma visão simples e rápida da experiência de sobrevivência, e o modelo de regressão de riscos proporcionais de Cox continua sendo o método de análise dominante. Este seminário introduz procedimentos e descreve a codificação necessária no SAS para modelar dados de sobrevivência por meio desses dois métodos, bem como muitas técnicas para avaliar e possivelmente melhorar o modelo. Ênfase particular é dada ao processo de estimativa de estimação não-paramétrica, e proc phreg para regressão de Cox e avaliação de modelo. Nota: Várias subseções são intituladas Background. Estes fornecem alguns dados 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 no SAS. Estes podem ser removidos ou expandidos no futuro. Nota: Os termos evento e falha são usados ​​de maneira intercambiável neste seminário, assim como o tempo até o evento e o tempo de falha. 1.1 Conjunto de dados de amostra Neste seminário, analisaremos os dados de 500 indivíduos do Estudo de Ataque Cardíaco de Worcester (referido a seguir como WHAS500, distribuído com Hosmer Lemeshow (2008)). Este estudo analisou vários fatores, como idade, sexo e IMC, que podem influenciar o tempo de sobrevida após o infarto. O tempo de seguimento para todos os participantes começa no momento da admissão hospitalar após o ataque cardíaco e termina com morte ou perda de acompanhamento (censura). As variáveis ​​utilizadas no presente seminário são: lenfol: duração do acompanhamento, terminada por morte ou censura. O resultado neste estudo. fstat: variável de censura, perda do acompanhamento0, morte1 idade: idade da internação IMC: índice de massa corporal hr: frequência cardíaca inicial gênero: masculino0, feminino1 Os dados do WHAS500 estão sujeitos apenas à censura à direita. Isto é, para alguns sujeitos não sabemos quando eles morreram após um ataque cardíaco, mas sabemos pelo menos quantos dias eles sobreviveram. 1.2. Antecedentes: Distribuições importantes na análise de sobrevivência A compreensão da mecânica por trás da análise de sobrevivência é auxiliada pela facilidade com as distribuições usadas, 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. Background: 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 em relação a todos os outros tempos de sobrevivência é conhecida como a função de densidade de probabilidade (pdf) ou f (t). Integrar o pdf em uma faixa de tempos de sobrevivência dá a probabilidade de observar um tempo de sobrevivência dentro desse intervalo. Por exemplo, se se sabe que os tempos de sobrevivência são 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 ter uma ideia de como é o uso de métodos não paramétricos em SAS com proc univariate. Aqui vemos o pdf estimado dos tempos de sobrevivência no conjunto whas500, do qual todas as observações censuradas foram removidas para ajudar na apresentação e explicação. No gráfico acima, vemos a correspondência entre pdfs e histogramas. Funções de densidade são essencialmente histogramas compostos de caixas de larguras pequenas. No entanto, em ambos podemos ver que nesses dados, os tempos de sobrevida mais curtos são mais prováveis, indicando que o risco de ataque cardíaco é forte inicialmente e diminui conforme o tempo passa. (Tecnicamente, porque não há tempos menores que 0, não deve haver gráfico à esquerda de LENFOL0) 1.2.2. Background: A função de distribuição cumulativa, F (T) A função de distribuição cumulativa (cdf), F (t), descreve a probabilidade de observar o tempo menor ou igual a algum tempo t, ou Pr (Timele t). Acima descrevemos que integrar o pdf em algum intervalo produz a probabilidade de observar o Tempo nesse intervalo. 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 e o pdf também implica: No SAS, podemos representar graficamente uma estimativa do cdf usando proc univariate. No gráfico acima, podemos ver que a probabilidade de sobreviver 200 dias ou menos é próxima de 50. Assim, em 200 dias, um paciente acumulou um pouco de risco, que se acumula mais lentamente após esse ponto. Em intervalos em que os tempos de evento são mais prováveis ​​(aqui os intervalos iniciais), o cdf aumentará mais rapidamente. 1.2.3. Antecedentes: A função Survival, S (t) Uma transformação simples da função de distribuição cumulativa produz a função de sobrevivência, S (t): A função survivor, S (t), descreve a probabilidade de sobreviver ao tempo passado t, ou Pr (Tempo t). Se fôssemos plotar a estimativa de S (t), veríamos que é um reflexo de F (t) (sobre y0 e deslocado para cima em 1). Aqui usamos proc lifestest para representar graficamente S (t). Parece que a probabilidade de sobreviver além de 1000 dias é um pouco menor que 0,2, o que é confirmado pelo cdf acima, onde vemos que a probabilidade de sobreviver a 1000 dias ou menos é um pouco mais que 0,8. 1.2.4. Antecedentes: A função de risco, h (t) O foco primário 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 risco, então, descreve a relação probabilidade do evento ocorrer no tempo t (f (t)), condicionado à sobrevivência dos sujeitos até aquele momento t (S (t)). A taxa de risco, portanto, descreve a taxa instantânea de falha no tempo t e ignora o acúmulo de perigo até o tempo t (ao contrário de F (t) e S (t)). Podemos estimar que a função de risco também é SAS usando proc lifestest: Como vimos anteriormente, o perigo parece ser maior no início do tempo de acompanhamento e, em seguida, declina rapidamente e finalmente estabiliza. Na verdade, a taxa de risco logo no início é mais de 4 vezes maior do que o risco de 200 dias depois. Assim, no início do estudo, esperávamos cerca de 0,008 falhas por dia, enquanto 200 dias depois, para aqueles que sobreviveram, esperávamos 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 indica, acumula riscos ao longo do tempo. Ele é calculado integrando a função de perigo em um intervalo de tempo: Vamos pensar novamente na função de risco, h (t), como a taxa na qual as falhas ocorrem no tempo t. Vamos supor ainda, para fins ilustrativos, que a taxa de risco permaneça constante na frac (x número de falhas por unidade de tempo t) ao longo do intervalo 0, t. Somando ao longo de todo o intervalo, então, nós esperamos observar x falhas, como frac t x, (assumindo que falhas repetidas são possíveis, tal que falhar não remove uma da observação). Uma interpretação da função de risco cumulativa é, portanto, o número esperado de falhas ao longo do intervalo de tempo 0, t. Não é de todo necessário que a função de risco permaneça constante para que a interpretação acima da função de risco cumulativo seja mantida, 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 risco descreve a taxa na qual os perigos são acumulados 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 de risco cumulativo H (t) e a função de sobrevivência S (t) tem uma relação monótona simples, tal 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 cumulativa está no seu mínimo. À medida que o tempo avança, a função Sobrevivência prossegue em direção ao mínimo, enquanto a função de risco acumulado prossegue até o máximo. A partir dessas equações, também podemos ver que esperamos que o pdf, f (t), seja alto quando h (t) a taxa de risco é alta (o começo, neste estudo) e quando o risco cumulativo H (t) é baixo (o começo, para todos os estudos). Em outras palavras, esperamos encontrar muitos tempos de falha em um determinado intervalo de tempo se 1) a taxa de risco for alta e 2) ainda houver muitos assuntos em risco. Podemos estimar a função de risco cumulativo usando o proc lifestest. os resultados dos quais enviamos para proc sgplot para plotagem. Observamos um aumento mais acentuado no risco acumulado no início do tempo de análise, refletindo a maior taxa de risco durante esse período. 2. Preparação e exploração de dados 2.1. Estrutura dos dados Este seminário cobre tanto proc lifestest quanto proc phreg. e os dados podem ser estruturados em uma das duas maneiras de análise de sobrevivência. Primeiro, 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 no acompanhamento Tempo. Tanto proc lifetest quanto proc phreg aceitarão dados estruturados dessa maneira. Os dados do WHAS500 são estruturados dessa maneira. Observe que há uma linha por assunto, com uma variável codificando o tempo para o evento, lenfol: vemos na tabela acima, que o assunto típico em nosso conjunto de dados é mais provável do sexo masculino, 70 anos de idade, com IMC de 26,6 e coração taxa de 87. O tempo médio para o evento (ou perda de acompanhamento) é de 882,4 dias, não uma quantidade particularmente útil. Todas essas variáveis ​​variam um pouco nesses dados. A maioria das variáveis ​​é pelo menos ligeiramente correlacionada com as outras variáveis. 3. Análise de Sobrevivência Não-paramétrica (descritiva) usando procetyetest 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, ambos no momento 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 sobreviveu até o tempo ti. A estimativa da função de sobrevivência da probabilidade incondicional de sobrevivência além do tempo t (a probabilidade de sobrevivência além do tempo t desde o início do risco) é então obtida pela multiplicação dessas probabilidades condicionais até o momento t. Olhando para a tabela de Estimativas de Sobrevivência com Limite do Produto abaixo, para o primeiro intervalo, de 1 dia até um pouco antes de 2 dias, ni 500, di 8, assim com S (1) frac 0.984. A probabilidade de sobreviver ao próximo intervalo, de 2 dias a pouco antes de 3 dias, durante os quais outras 8 pessoas morreram, dado que o sujeito sobreviveu a 2 dias (a probabilidade condicional) é de 0,98374. A probabilidade incondicional de sobreviver além dos 2 dias (a partir do início do risco) é, então, hat S (2) frac timesfrac 0,984times0,98374.9680 3.1.2. Obtenção e interpretação de tabelas de Kaplan-Meier As estimativas de sobrevivência geralmente começam com o exame da experiência global de sobrevivência por meio de métodos não paramétricos, como Kaplan-Meier (limite de produto) e estimadores de tábua de vida da função de sobrevivência. Os métodos não paramétricos são atraentes porque não é necessário assumir a forma da função de sobrevivente nem da função de perigo. However, nonparametric methods do not model the hazard rate directly nor do they estimate the magnitude of the effects of covariates. In the code below, we show how to obtain a table and graph of the Kaplan-Meier estimator of the survival function from proc lifetest : At a minimum proc lifetest requires specification of a failure time variable, here lenfol. on the time statement. Without further specification, SAS will assume all times reported are uncensored, true failures. Thus, because many observations in WHAS500 are right-censored, we also need to specify a censoring variable and the numeric code that identifies a censored observation, which is accomplished below with fstat(0). All numbers within the parentheses are treated as indicators for censoring, which implies that all numbers excluded from the parentheses are treated as indicators that the event occurred. We also specify the option atrisk on the proc lifetest statement to display the number at risk in our sample at various time points. Product-Limit Survival Estimates Above we see the table of Kaplan-Meier estimates of the survival function produced by proc lifetest. Each row of the table corresponds to an interval of time, beginning at the time in the LENFOL column for that row, and ending just before the time in the LENFOL column in the first subsequent row that has a different LENFOL value. For example, the time interval represented by the first row is from 0 days to just before 1 day. In this interval, we can see that we had 500 people at risk and that no one died, as Observed Events equals 0 and the estimate of the Survival function is 1.0000. During the next interval, spanning from 1 day to just before 2 days, 8 people died, indicated by 8 rows of LENFOL1.00 and by Observed Events8 in the last row where LENFOL1.00. It is important to note that the survival probabilities listed in the Survival column are unconditional . and are to be interpreted as the probability of surviving from the beginning of follow up time up to the number days in the LENFOL column. Lets take a look at later survival times in the table: Product-Limit Survival Estimates From LENFOL368 to 376, we see that there are several records where it appears no events occurred. These are indeed censored observations, further indicated by the appearing in the unlabeled second column. Subjects that are censored after a given time point contribute to the survival function until they drop out of the study, but are not counted as a failure. We can see this reflected in the survival function estimate for LENFOL382. During the interval 382,385) 1 out of 355 subjects at-risk died, yielding a conditional probability of survival (the probability of survival in the given interval, given that the subject has survived up to the begininng of the interval) in this interval of frac 0.9972. We see that the uncoditional probability of surviving beyond 382 days is .7220, since hat S(382)0.7220p(surviving days)times0.9971831, we can solve for p(surviving days)frac .7240. In the table above, we see that the probability surviving beyond 363 days 0.7240, the same probability as what we calculated for surviving up to 382 days, which implies that the censored observations do not change the survival estimates when they leave the study, only the number at risk. 3.1.3. Graphing the Kaplan-Meier estimate Graphs of the Kaplan-Meier estimate of the survival function allow us to see how the survival function changes over time and are fortunately very easy to generate in SAS: By default, proc lifetest graphs the Kaplan Meier estimate, even without the plot option on the proc lifetest statement, so we could have used the same code from above that produced the table of Kaplan-Meier estimates to generate the graph. However, we would like to add confidence bands and the number at risk to the graph, so we add plotssurvival(atrisk cb) . The step function form of the survival function is apparent in the graph of the Kaplan-Meier estimate. When a subject dies at a particular time point, the step function drops, whereas in between failure times the graph remains flat. The survival function drops most steeply at the beginning of study, suggesting that the hazard rate is highest immediately after hospitalization during the first 200 days. Censored observations are represented by vertical ticks on the graph. Notice the survival probability does not change when we encounter a censored observation. Because the observation with the longest follow-up is censored, the survival function will not reach 0. Instead, the survival function will remain at the survival probability estimated at the previous interval. The survival function is undefined past this final interval at 2358 days. The blue-shaded area around the survival curve represents the 95 confidence band, here Hall-Wellner confidence bands. This confidence band is calculated for the entire survival function, and at any given interval must be wider than the pointwise confidence interval (the confidence interval around a single interval) to ensure that 95 of all pointwise confidence intervals are contained within this band. Many transformations of the survivor function are available for alternate ways of calculating confidence intervals through the conftype option, though most transformations should yield very similar confidence intervals. 3.2. Nelson-Aalen estimator of the cumulative hazard function Because of its simple relationship with the survival function, S(t)e , the cumulative hazard function can be used to estimate the survival function. The Nelson-Aalen estimator is a non-parametric estimator of the cumulative hazard function and is given by: where di is the number who failed out of ni at risk in interval ti. The estimator is calculated, then, by summing the proportion of those at risk who failed in each interval up to time t. The Nelson-Aalen estimator is requested in SAS through the nelson option on the proc lifetest statement. SAS will output both Kaplan Meier estimates of the survival function and Nelson-Aalen estimates of the cumulative hazard function in one table. Survival Function and Cumulative Hazard Rate Lets confirm our understanding of the calculation of the Nelson-Aalen estimator by calculating the estimated cumulative hazard at day 3: hat H(3)frac frac frac 0.0385, which matches the value in the table. The interpretation of this estimate is that we expect 0.0385 failures (per person) by the end of 3 days. The estimate of survival beyond 3 days based off this Nelson-Aalen estimate of the cumulative hazard would then be hat 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. respectivamente. 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 martingal e 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 em particular pela Universidade da Califórnia.

Комментариев нет:

Отправить комментарий