Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

Uma Introdução ao R
Tabela de Conteúdos
Uma Introdução ao R Prefácio 1 Introdução e preliminares 1.1 R O ambiente 1,2 software e documentação relacionada 1,3 R e estatísticas 1,4 R eo sistema de janelas 1.5 Usando R interativamente Uma sessão introdutória 1,6 1,7 Obter ajuda com funções e características 1,8 comandos R, maiúsculas e minúsculas, etc Lembre-se 1,9 e correção dos comandos anteriores 1,10 executar comandos a partir de ou desviar a saída para um arquivo 1,11 permanência de dados e objetos de remoção Duas manipulações simples, números e vetores 2,1 Vetores e atribuição 2,2 aritmética Vector 2,3 gerar seqüências regulares 2,4 vetores lógicos 2,5 valores em falta 2,6 Personagem vetores Índice de 2,7 vetores; seleção e modificação de subconjuntos de um conjunto de dados 2,8 Outros tipos de objetos 3 Objetos, seus modos e atributos 3,1 atributos intrínsecos: modo e tempo 3.2 Alterando o comprimento de um objeto 3,3 obter e definir atributos 3,4 A classe de um objeto 4 e ordenada desordenadas fatores Um exemplo específico 4,1 4.2 A função tapply() e matrizes irregulares 4,3 fatores ordenada 5 matrizes e matrizes 5,1 Arrays 5,2 a indexação de matriz. Subseções de uma matriz 5,3 matrizes Índice 5.4 O array() função 5.4.1 vetores e aritmética mista matriz. A regra da reciclagem 5,5 exterior O produto de duas matrizes 5,6 transposição generalizada de uma matriz 5,7 instalações Matrix 5.7.1 A multiplicação de matrizes 5.7.2 equações lineares e inversão 5.7.3 Autovalores e autovetores 5.7.4 decomposição em valores singulares e determinantes 5.7.5 ajuste dos mínimos quadrados e decomposição QR 5,8 Formação matrizes particionadas, cbind() e rbind()

1 de 99

25/02/2011 10:36

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

5,9 concatenação A função, c() , com matrizes 5,10 tabelas de freqüência de fatores 6 listas e quadros de dados Listas de 6,1 6,2 Construir e modificar listas 6.2.1 Listas de concatenação 6,3 quadros de dados 6.3.1 Fazendo quadros de dados 6.3.2 attach() and detach() 6.3.3 Trabalhando com quadros de dados 6.3.4 Anexando listas arbitrárias 6.3.5 Gerenciando o caminho de pesquisa 7 Os dados de leitura de arquivos 7.1 O read.table() função 7.2 A scan() função 7,3 datasets Acessando builtin 7.3.1 Carregando dados a partir de R outros pacotes 7,4 Editando dados 8 As distribuições de probabilidade 8,1 R, um conjunto de quadros estatísticos 8,2 Examinando a distribuição de um conjunto de dados 8,3 e dois testes de amostra de um 9 Agrupamento, loops e execução condicional 9,1 expressões Agrupado 9,2 Instruções de controle 9.2.1 Execução condicional: if as declarações 9.2.2 execução repetitiva: for loops, repeat e while 10 Escrevendo suas próprias funções 10,1 exemplos simples 10,2 definir novos operadores binários 10,3 argumentos nomeados e padrões 10.4 A '...' argumento 10,5 atribuições dentro de funções 10,6 exemplos mais avançados 10.6.1 Os factores de eficiência em blocos 10.6.2 descartando todos os nomes em uma matriz impressa 10.6.3 integração numérica recursiva 10,7 Âmbito 10,8 Personalizando o ambiente 10,9 Classes, funções genéricas e orientação a objetos 11 modelos estatísticos em R 11,1 Definição de modelos estatísticos, fórmulas 11.1.1 Contrastes 11,2 modelos lineares 11,3 funções genéricas para extrair informações sobre o modelo 11.4 Análise de variância e um modelo de comparação 11.4.1 tabelas ANOVA 11,5 Atualizando modelos equipados 11,6 modelos lineares generalizados 11.6.1 Famílias 11.6.2 O glm() função 11,7 mínimos quadrados não-lineares e modelos de máxima verossimilhança 11.7.1 Método dos mínimos quadrados 11.7.2 máxima verossimilhança

2 de 99

25/02/2011 10:36

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

11,8 Alguns modelos não-standard 12 procedimentos Gráfica 12,1 alto nível comandos de plotagem 12.1.1 A plot() função 12.1.2 Resultados de dados multivariados 12.1.3 Artes gráficas 12.1.4 Argumentos para alto nível de plotagem funções 12,2 baixo nível de comandos de plotagem 12.2.1 anotação Matemática 12.2.2 fontes Hershey vetor 12,3 Interagindo com gráficos 12.4 Usando parâmetros gráficos 12.4.1 mudanças permanentes: O par() função 12.4.2 mudanças temporárias: Argumentos para funções gráficas 12,5 Graphics lista de parâmetros 12.5.1 Os elementos gráficos 12.5.2 eixos e marcas de escala 12.5.3 margens Figura 12.5.4 ambiente figura múltipla 12,6 drivers de dispositivos 12.6.1 diagramas PostScript para escrever documentos 12.6.2 múltiplos dispositivos gráficos 12,7 gráficos dinâmicos 13 Pacotes 13,1 pacotes Standard 13,2 pacotes de Contribuição e CRAN 13,3 Namespaces Apêndice sessão de amostra AA Apêndice B Invocando R B.1 R Invocando a partir da linha de comando B.2 Invocando R no Windows B.3 Invocando R no Mac OS X B.4 Script com R Apêndice C A linha de comando-editor Preliminares C.1 Edição de ações C.2 Editor de resumo de linha de comando C.3 Apêndice D Função e índice variável Apêndice E índice Concept Referências Apêndice F Seguinte: Prefácio , Precedente: (dir) , Up: (dir)

Uma Introdução ao R
Esta é uma introdução ao R ("GNU S"), uma linguagem e ambiente para computação estatística e gráficos. R é similar ao sistema S premiada, que foi desenvolvido nos Laboratórios Bell por John Chambers et al. Ele fornece uma ampla variedade de técnicas estatísticas e gráficas (modelagem linear e não linear, testes estatísticos, análise de séries temporais, classificação, agrupamento, ...). Este manual fornece informações sobre tipos de dados, elementos de programação, modelagem estatística e gráficos. A versão atual deste documento é 2.12.1 (2010/12/16).

3 de 99

25/02/2011 10:36

Comentários e correções são sempre bem vindos.Uma Introdução ao R http://translate. e por ser um defensor da R do caminho de volta. Introdução e preliminares Seguinte: manipulações simples números e vetores . Isto deve dar alguma familiaridade com o estilo de R sessões e mais importante feedback algum instante sobre o que realmente acontece. Por favor. Neste caso. endereço para correspondência e-mail para R-core@R-project. Fizemos uma série de pequenas alterações para refletir as diferenças entre os programas R e S. Up: Top Prefácio Esta introdução para R é derivado de um original conjunto de notas que descrevam o S-PLUS e ambientes S escrito em 1990-2 por Bill Venables e David M. Anterior: Prefácio . Sugestões para o leitor A maioria dos novatos R começará com a sessão introdutória no Apêndice A. e ampliou alguns dos materiais. Anterior: Top . gráficos sobre as instalações de gráficos pode ser lido em quase todo o tempo e não precisa esperar até que todas as seções anteriores foram digeridas. Gostaríamos de agradecer sinceramente a Bill Venables (e David Smith) para a concessão de permissão para distribuir esta versão modificada das notas. Muitos usuários chegará a R principalmente para as suas instalações gráficas. ISBN 3-900051-12-7 Prefácio Introdução e preliminares Simples números manipulações e vetores Objetos Fatores Matrizes e matrizes Listas e quadros de dados Lendo dados de arquivos As distribuições de probabilidade Loops e execução condicional Escrever suas próprias funções Os modelos estatísticos em R Gráficos Pacotes A sessão de exemplo Invocando R A linha de comando-editor e variável índice de Função Conceito de índice Referências Seguinte: Introdução e preliminares .googleusercontent. Up: Top 1 Introdução e preliminares 4 de 99 25/02/2011 10:36 ..com/translate_c?hl=pt-BR&ie=UTF-. Smith quando da Universidade de Adelaide. desta forma.org ..

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

O ambiente R Related software e documentação R e estatísticas R eo sistema de janelas Usando R interativamente Obter ajuda R comandos; maiúsculas e minúsculas etc Recall e correção dos comandos anteriores A execução de comandos de saída ou o desvio para um arquivo Dados permanência e removendo objetos Seguinte: software e documentação relacionada , Anterior: Introdução e preliminares , Up: Introdução e preliminares 1,1 O ambiente R R é um conjunto integrado de recursos de software para manipulação de dados, cálculo e exibição gráfica. Entre outras coisas, ele tem um tratamento eficaz de dados e instalação de armazenamento, um conjunto de operadores para cálculos em matrizes, matrizes em particular, um grande conjunto coerente e integrado de ferramentas de intermediário para a análise dos dados, facilidades gráficas para análise de dados e exibir diretamente no computador ou em cópia impressa e uma linguagem de programação bem desenvolvida, simples e eficaz (chamado `S '), que inclui condicionais, loops, funções definidas pelo usuário recursiva e facilidades de entrada e saída. (Na verdade a maioria das funções do sistema fornecidos são escritos na linguagem de S). O termo "ambiente" destina-se a caracterizá-lo como um sistema totalmente planejada e coerente, ao invés de uma acumulação gradual de ferramentas muito específicas e rígidas, como é frequentemente o caso com outros softwares de análise de dados. R é muito mais um veículo para desenvolver novos métodos de análise de dados interativa. Ele se desenvolveu rapidamente, e foi prorrogado por uma grande coleção de pacotes. No entanto, a maioria dos programas escritos em R são essencialmente efêmeros, escrito por uma única peça de análise de dados. Seguinte: R e estatísticas , Precedente: R ambiente A , Up: Introdução e preliminares 1,2 software e documentação relacionada R pode ser considerada como uma implementação da linguagem de S, que foi desenvolvido nos Laboratórios Bell por Rick Becker, John Chambers Wilks e Allan, e também forma a base dos sistemas S-P LUS. A evolução da linguagem é caracterizada por quatro livros por John Chambers e co-autores. Por R, a referência básica é o novo S Idioma: Um ambiente de programação para análise de dados e imagens por Richard A. Becker, M. e R. John Chambers Allan Wilks. As novas características da versão 1991 do S são abordados em Modelos Estatísticos em S editado por John Chambers M. e J. Trevor Hastie. Os métodos formais e classes do pacote são baseados em métodos daqueles descritos na programação com dados por John M. Chambers. Veja Referências , referências precisas.

5 de 99

25/02/2011 10:36

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

Há agora uma série de livros que descrevem como usar o R para análise de dados e estatísticas e documentação para o S / S-PLUS pode ser usado tipicamente com R, mantendo as diferenças entre as implementações S em mente. Consulte a documentação que existe para R? . Seguinte: R eo sistema de janelas , Precedente: software e documentação relacionada , Up: Introdução e preliminares 1,3 R e estatísticas Nossa introdução ao ambiente de R não mencionou as estatísticas, mas muitas pessoas usam R como um sistema de estatísticas. Nós preferimos pensar que de um ambiente no qual muitos clássicas e modernas técnicas estatísticas têm sido implementadas. Alguns destes são incorporados ao ambiente R base, mas muitos são oferecidos como pacotes. Há cerca de 25 pacotes fornecidos com R (chamada de "padrão" e "recomenda" pacotes) e muitos mais estão disponíveis através da família CRAN de sites da Internet (via http://CRAN.R-project.org ) e em outros lugares. Mais detalhes sobre os pacotes são dadas mais tarde (ver pacotes ). A maioria das estatísticas clássicas e muito mais nova metodologia está disponível para uso com R, mas os usuários podem precisar de ser preparado para fazer um pouco de trabalho para encontrá-lo. Há uma importante diferença de filosofia entre S (e, portanto, R) e os outros principais sistemas estatísticos. Em uma análise estatística S é normalmente feito como uma série de etapas, com resultados intermediários sendo armazenados nos objetos. Assim, enquanto a SAS e SPSS dará saída abundante de uma análise de regressão ou discriminante, R dará saída mínima e armazenar os resultados em um objeto adequado para posterior interrogatório por funções mais R. Próximo: Usando R interativamente , Precedente: R e estatísticas , Up: Introdução e preliminares 1,4 R eo sistema de janelas A maneira mais conveniente de usar R está em uma estação de trabalho gráfico com um sistema de janelas. Este guia é dirigido aos usuários que têm essa facilidade. Em particular, ocasionalmente se referem ao uso de R em um sistema de janelas X, embora a grande maioria do que é dito é de aplicação geral a qualquer aplicação do ambiente R. A maioria dos usuários acham necessário interagir diretamente com o sistema operacional em seu computador de vez em quando. Neste guia, principalmente discutir a interação com o sistema operacional em máquinas UNIX. Se você estiver executando o R no Windows ou Mac OS você vai precisar fazer alguns pequenos ajustes. Configurando uma estação de trabalho para tirar o máximo proveito dos recursos personalizáveis de R é um procedimento simples mas um pouco tedioso, e não será considerada mais aqui. Usuários em dificuldade deve procurar ajuda especializada local. Seguinte: Como obter ajuda , Precedente: R eo sistema de janelas , Up: Introdução e preliminares 1.5 Usando R interativamente Quando você usa o programa R emite um alerta quando se espera que os comandos de entrada. O aviso padrão é ' > ', que em UNIX pode ser o mesmo que a janela de comandos, e assim pode parecer que nada está acontecendo. No entanto, como veremos, é fácil de mudar para um R prompt diferente se desejar. Vamos supor que o shell do UNIX prompt é ' $ '. Ao utilizar o R no UNIX o procedimento sugerido para o primeiro é o seguinte:

6 de 99

25/02/2011 10:36

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

1. Criar um sub-diretório separado, dizem que o trabalho, para armazenar arquivos de dados em que você vai usar R para este problema. Este será o diretório de trabalho sempre que você usar R para este problema particular.
$ Mkdir work $ Cd work

2. Inicie o programa R com o comando
R $

3. Neste ponto R comandos podem ser emitidos (ver adiante). 4. Para encerrar o programa R, o comando é
> Q ()

Neste ponto, você será perguntado se deseja salvar os dados da sua sessão R. Em alguns sistemas, isso fará com que uma caixa de diálogo, e em outros que você irá receber um prompt para que você possa responder sim, não ou cancelar (uma abreviação de letra vai fazer) para salvar os dados antes de sair, sair sem salvar, ou retornar para a sessão R. Dados que é salvo estará disponível em futuras sessões R. outras sessões R são simples. 1. Fazer o trabalho do diretório de trabalho e iniciar o programa como antes:
$ Cd work R $

2. Use o programa R, que encerra com a q() o comando no final da sessão. Para usar o R no Windows o procedimento a seguir é basicamente o mesmo. Crie uma pasta como a pasta de trabalho, e definir que, no campo Iniciar Em seu atalho R. Em seguida, inicie R clicando duas vezes sobre o ícone. 1,6 Uma sessão introdutória Os leitores que quiserem ter uma idéia de R em um computador antes de prosseguir são fortemente aconselhados a trabalhar com a sessão introdutória dada em uma sessão de amostra . Seguinte: R comandos; maiúsculas e minúsculas etc , Anterior: Usando R interativamente , Up: Introdução e preliminares 1,7 Obter ajuda com funções e características R tem um mecanismo de ajuda inbuilt semelhante ao man facilidade de UNIX. Para obter mais informações sobre qualquer chamada função específica, por exemplo, solve , o comando é
> Ajuda (resolver)

Uma alternativa é
>? Resolver

Para um recurso especificado por caracteres especiais, o argumento deve ser colocado entre aspas simples ou duplas, tornando-se uma "cadeia de caracteres": Essa também é necessário para algumas palavras com significado sintático, incluindo if , for e function .
> Ajuda ("[[")

7 de 99

25/02/2011 10:36

tudo até o fim da linha é um comentário . O conjunto de símbolos que podem ser usados em nomes de R depende do sistema operacional e do país em que R está sendo executado (tecnicamente na localidade em uso). impressa (salvo se tornado invisível). " e ' _ '. É sensível como a maioria dos pacotes base UNIX. eo valor é perdido. por isso A e a são diferentes símbolos e remete para as diferentes variáveis.search comando (em alternativa ?? ) permite procurar ajudar de várias formas. '). por meio 8 de 99 25/02/2011 10:36 .start () que vai lançar um navegador da Web que permite que as páginas de ajuda para serem acessadas por hiperlinks. Na maioria das instalações de R ajuda está disponível em formato HTML. ' ou uma letra.search para mais detalhes e mais exemplos. Se um comando não está completa no final de uma linha. ' o segundo personagem não deve ser um dígito.. mas o resultado não é impresso automaticamente. Os nomes são actualmente limitado a 256 bytes. Anterior: Obtendo ajuda . isso inclui os caracteres acentuados) plus ' . com a restrição de que um nome deve começar com' . comandos Fundamental consistir em expressões e atribuições. Pode ser uma ótima maneira de se orientar rapidamente e entender a amplitude do que R tem para oferecer. Comentários podem ser colocados quase dois em qualquer lugar. A cessão também avalia uma expressão e passa o valor para uma variável. ou por uma nova linha. Up: Introdução e preliminares 1. os pedidos de ajuda subseqüentes são enviadas para o sistema de ajuda baseado em HTML.start() é particularmente útil. começando com uma cancela (' # ').. Os exemplos em um tópico de ajuda pode normalmente ser executado por > Example (topic) A versões Windows do R ter outros sistemas de ajuda opcionais: use >? Ajuda para mais detalhes. Se uma expressão é dada como um comando. Qualquer forma de aspas pode ser usado para escapar do outro.googleusercontent. que busca ainda funções disponíveis. Normalmente todos os símbolos alfanuméricos são permitidos um (e em alguns países. >? Resolver Tentar ?help. O help. R dará um padrão diferente pronta. O «motor e palavras-chave 'do link da pesquisa na página carregada pelo help.Uma Introdução ao R http://translate. como na seqüência "It's important" . maiúsculas e minúsculas. ele é avaliado. de preferência. Por exemplo. comandos elementares podem ser agrupadas em uma expressão composta por chaves (' { 'e' } '). etc Tecnicamente R é uma linguagem de expressão com uma sintaxe muito simples. pois é conceito contém uma lista de alto nível. executando > Help.com/translate_c?hl=pt-BR&ie=UTF-. Os comandos são separados por um ponto e vírgula (' . No UNIX. Seguinte: Recall e correção dos comandos anteriores . e se inicia com ' .8 comandos R. Nossa convenção é usar aspas duplas.

Uma Introdução ao R http://translate. > Pia ("record. Mais detalhes são fornecidos mais tarde: ver a linha de comando-editor . Emacs Speaks Statistics) para trabalhar interativamente com R. Seguinte: Dados permanência e remoção de objetos . O comando > Pia () restaura-lo para o console novamente. maiúsculas e minúsculas etc . A função de sink . funções ou estruturas mais gerais construídos a 9 de 99 25/02/2011 10:36 . digamos commands.9 e correção dos comandos anteriores De acordo com várias versões do UNIX e Windows. As linhas de comando digitada no console são limitados 3 a cerca de 4095 bytes (caracteres não). A capacidade de convocação e de edição em UNIX são altamente personalizáveis. Você pode descobrir como fazer isso lendo o manual de entrada para a biblioteca readline. R fornece um mecanismo para chamar e re-execução de comandos anteriores... Anterior: A execução de comandos de saída ou o desvio para um arquivo . o editor de texto Emacs fornece mecanismos de apoio mais geral (por meio de ESS. Up: Introdução e preliminares Lembre-se 1. Como alternativa. Up: Introdução e preliminares 1.lis") irá desviar todas as saídas subseqüentes do console para um arquivo externo. Uma vez que o comando está localizado.googleusercontent.R na obra diretório de trabalho. matrizes de números.com/translate_c?hl=pt-BR&ie=UTF-. o cursor pode ser movido dentro do comando usando as teclas de seta horizontal.11 permanência de dados e objetos de remoção As entidades que R cria e manipula são conhecidos como objetos. Precedente: Recall e correção dos comandos anteriores . Precedente: R comandos.lis. Nós geralmente omitem a continuação pronta e indicar a continuidade de recuo simples. Ver R e Emacs . Esta pergunta pode ser alterada pelo usuário. desta forma. eles podem ser executados a qualquer momento em uma sessão de R com o comando > Fonte ("commands.R") Para Fonte do Windows também está disponível no menu Arquivo. As teclas de seta vertical no teclado pode ser usado para rolar para frente e para trás através de uma história de comando. Próximo: Executando comandos a partir de ou desviar a saída para um arquivo . e os personagens podem ser removidos com a chave <DEL> ou adicionados com as outras teclas. + no segundo e subseqüentes linhas e continuar a ler a entrada até que o comando é sintaticamente completa. seqüências de caracteres. record. Estas podem ser variáveis.10 executar comandos a partir de ou desviar a saída para um arquivo Se os comandos quatro são armazenados em um arquivo externo. Up: Introdução e preliminares 1.

use o comando R > X <. números e vetores Vetores e atribuição aritmética Vector regular gerar seqüências Lógico vetores Os valores em falta Personagem vetores Índice de vetores Outros tipos de objetos Seguinte: Vector aritmética . temp.7. 6 10 de 99 25/02/2011 10:36 .4. Anterior: Introdução e preliminares . É bastante comum para objetos com nomes x e y a ser criado durante a análise. ou seja. z.6. 10.. digamos. 3.4. neste contexto pode ter um número arbitrário de argumentos de vetor e cujo valor é um vetor tem concatenando seus argumentos finais até ao fim. o associado do histórico dos comandos é recarregada. que é uma entidade única. Rdata 5 no diretório atual.7) Esta é uma declaração de atribuição usando a função c() que. A estrutura mais simples como é o vetor numérico.4 e 21. foo. 21. Recomenda-se que você deve usar separar diretórios de trabalho para as análises efectuadas com R.Uma Introdução ao R http://translate. 6. 5.c (10. e as linhas de comando usado na sessão são salvos em um arquivo chamado. Para configurar um vetor denominado x . Se você indicar que você quer fazer isso.1. A coleção de objetos armazenados atualmente é chamado o espaço de trabalho. partir de tais componentes. Para remover objetos da função rm está disponível: > Rm (x. bar) Todos os objetos criados durante uma sessão de R pode ser armazenado permanentemente em um arquivo para uso em futuras sessões R. Durante uma sessão I. mas pode ser bastante difícil decidir o que pode ser quando as análises foram conduzidas várias no mesmo diretório. 6.. No final de cada sessão R é-lhe dada a oportunidade de salvar todos os objetos disponíveis no momento. anterior: Simple números manipulações e vetores .1 Vetores e atribuição R opera sobre estruturas de dados nomeado. Ao mesmo tempo. 3. tinta. consistindo de cinco números. 5.1. Rhistory. Up: Simple números manipulações e vetores 2. os objetos são criados e armazenados pelo nome (discutiremos esse processo na próxima sessão). Nomes como este são muitas vezes significativos no contexto de uma única análise. Up: Top Duas manipulações simples. que consiste em uma coleção ordenada de números. Seguinte: Objetos .6.4. os objetos são gravados em um arquivo chamado.googleusercontent. O comando R objetos> () (Alternativamente.com/translate_c?hl=pt-BR&ie=UTF-. y. Quando R é iniciado na tarde do mesmo diretório que recarrega o espaço de trabalho a partir deste arquivo. ls() ) pode ser usado para exibir os nomes dos (a maioria) os objetos que estão atualmente armazenados no R. sucata.

a ' = operador pode ser usado como uma alternativa. Então. 5. 0.4. max e min e selecionar o menor eo maior elementos de um vetor. Assim. Up: Simple números manipulações e vetores 2.2 aritmética Vector Vetores podem ser usados em expressões aritméticas.7)) O operador de costume. pode ser pensado como um sintática atalho para isso.4. c (10..'). Uma maneira equivalente de fazer a mesma tarefa como acima está com: > Assign ("x". cos . <. Na maioria dos contextos. sin ... . 6. Atribuições também pode ser feita em outra direção. 2*x 2.6. / e ^ para elevar a uma potência. Além de todas as funções aritméticas comuns estão disponíveis. log . * .1. Assim. vetores mais curtos na expressão são recicladas quantas vezes necessário (talvez fracionada). max(x)) . Duas funções estatísticas são mean(x) que calcula a média da amostra. todos têm seu significado usual. Seguinte: regular gerar seqüências . e var(x) que dá sum ((x-média (x)) ^ 2) / (comprimento (x) -1) 11 de 99 25/02/2011 10:36 ..2 repetidas vezes. o valor é impresso e perdeu 7 . c(min(x). exp . 5. que consiste de dois personagens do < "(" menor que ") e" .1. até que elas coincidam com o comprimento do maior vetor. x) criaria um vetor y com 11 entradas composto de duas cópias de x com um zero no lugar do meio. Observe que o operador de atribuição (' <. range é uma função cujo valor é um vetor de comprimento dois. elemento por elemento.2 * x + y + 1 gera um novo vetor v de comprimento 11 construído pela soma. se tivéssemos que usar o comando > 1 / x os inversos dos cinco valores seriam impressas no terminal (eo valor de x . é claro. A tarefa ainda mais <> Y . Os operadores aritméticos elementares são os habituais + . o valor da expressão é um vetor com o mesmo comprimento que o maior vetor. Em especial. e assim por diante.c (x. agora. a mesma atribuição pode ser feita usando > C (10. Se não forem.4. length(x) é o número de elementos em x .6. 21. uma constante é simplesmente repetido. tan . Um número que ocorre por si só.com/translate_c?hl=pt-BR&ie=UTF-. 3. Precedente: Vetores e atribuição . 3.Uma Introdução ao R http://translate. caso em que as operações são realizadas elemento por elemento. permanece inalterado). 6. e 1 repetido 11 vezes."(" menos ") que ocorrem estritamente lado a lado e` pontos 'para o objeto que recebe o valor da expressão. sqrt .googleusercontent. que ocorre na expressão. sum(x) dá o total dos elementos em x . que é a mesma sum(x)/length(x) . Vetores ocorrendo na mesma expressão não precisam ser todos do mesmo comprimento.7) -> x Se uma expressão é usada como um comando completo. com as atribuições acima do comando V <> .4. isto é. 21. y repetida apenas uma vez. em uma expressão é tida como um vetor de comprimento um. usando a evidente mudança de operador de atribuição. Atribuição também pode ser feita usando a função assign() . e prod(x) o seu produto. respectivamente.

especificar o início eo fim da seqüência. seq(from=1. mesmo se eles tiverem vários vetores.8. por exemplo 2*1:15 é o vetor c(2. from=1) são todos iguais como 1:30 .3 seqüências regulares R tem um número de instalações para a geração de seqüências comumente utilizado de números. Assim sqrt (-17) dará NaN e uma advertência. 5. mas sqrt (-17 0 i) fará os cálculos de números complexos. 30) . por isso. 29. . O valor máximo e mínimo de funções paralelas pmax e pmin retornar um vetor (de comprimento igual ao seu maior argumento) que contém em cada elemento o maior eo menor) elemento (em que a posição em qualquer um dos vetores de entrada. assim seq(1. Os primeiros dois argumentos.10 e comparar as seqüências 1:n-1 e 1:(n-1) .. 2) -> s3 gera em s3 o vetor c(-5.list() que produzem uma permutação para fazer a classificação) . 4.googleusercontent. por =. to=30) e seq(to=30. ..com/translate_c?hl=pt-BR&ie=UTF-.. Do mesmo modo 12 de 99 25/02/2011 10:36 . ou variância da amostra. só algumas das quais podem ser especificados em qualquer uma chamada. Os primeiros dois parâmetros pode ser chamado from= valor e to= valor. -4. Coloque n <. caso em que a ordem em que aparecem é irrelevante. Parâmetros para seq() . também pode ser dada em forma de nome. regular gerar seqüências Seguinte: vetores lógicos .. 5. Ela tem cinco argumentos... retorna um vetor do mesmo tamanho de x com os elementos dispostos em ordem crescente. Note-se que max e min e selecionar o menor eo maior valores em seus argumentos..0. . 4. A construção 30:1 pode ser usado para gerar uma seqüência para trás. 28. os cálculos são feitos com precisão dupla números reais ou números de precisão dupla complexo se os dados de entrada são complexas. se houver.6.0) . o padrão by=1 é assumido. Up: manipulações simples números e vetores Geração de 2. 2.. sort(x) Para trabalhar com números complexos.30) . Os próximos dois parâmetros para seq() pode ser chamado by= valor e length= valor. Por exemplo > Seq (-5. reais ou mesmo complexos.8. Precedente: aritmética Vector .. 4. A função seq() é um mecanismo mais geral para a geração de seqüências.6. -4.10) é o mesmo vetor como 2:10 .. porém existem outras instalações de classificação mais flexível disponível (veja a order() ou sort. e se estes são os dois únicos argumentos que apresenta o resultado é o mesmo que o operador dois pontos.. Por exemplo 1:30 é o vetor c(1. Para a maioria dos efeitos que o usuário não se preocupa se os "números" em um vetor numérico são inteiros. 30) . e para muitas funções R outro.Uma Introdução ao R http://translate. Se o argumento para var() é um n-por-p-valor da matriz é um sub-p-p covariância da amostra tem por matriz a respeito das linhas como independente variada amostra de vetores-p. fonte de uma parte explícita complexo. O operador dois pontos tem alta prioridade dentro de uma expressão. Se nenhum desses for dada. que especifica um tamanho de passo e um comprimento para a seqüência respectivamente. Isso é seq(2. Internamente.

caso em que são coagidos a vetores numéricos. atribuindo a ela o valor especial NA . qualquer operação realizada sobre um NA torna-se um NA .. Os dois primeiros são abreviadas como T e F . portanto. <= . por padrão.4 vetores lógicos Bem como vetores numéricos.x> 13 define temp como um vetor de mesmo comprimento que x .. 13 de 99 25/02/2011 10:36 . Os operadores lógicos são < . o resultado não pode ser conhecido e. Up: Simple números manipulações e vetores 2. um lugar dentro de um vetor pode ser reservado para ela. . cada = 5) que se repete cada elemento x cinco vezes antes de avançar para a próxima.rep (x. existem situações onde os vetores lógicos e seus homólogos coagido numéricos não são equivalentes. você deve sempre usar TRUE e FALSE . A função está relacionada rep() que pode ser usado para replicar um objeto de diversas maneiras complicadas. == para a igualdade exata e != para a desigualdade. length( vetor ) . Up: manipulações simples números e vetores 2. A motivação para esta regra é simplesmente que se a especificação de uma operação é incompleta. 2) gera o mesmo vetor em s4 .seq (length = 51. >= . > S4 <.na(x) dá um vetor lógico do mesmo tamanho de x com o valor TRUE se e somente se o elemento correspondente em x é NA . O quinto parâmetro pode ser nomeado along= vetor. vezes = 5) que vai colocar cinco cópias de x fim-de-final em s5 . e cria uma seqüência de 1. c1 & c2 é a intersecção (" ". portanto.5 valores em falta Em alguns casos. que se for utilizado deve ser o único parâmetro. pode ser substituído pelo usuário. Portanto. Os elementos de um vetor lógico pode ter os valores TRUE . se c1 e c2 são expressões lógicas. Lógico vetores são gerados por condições. respectivamente. Por exemplo <Temp> . a partir =. ou a seqüência vazia se o vetor está vazia (como pode ser ). > . veja abaixo). No entanto. com valores FALSE correspondentes aos elementos de x em que a condição não for cumprida e TRUE onde ela está.. Outra versão é útil <> S6 . FALSE . em seguida. Lógico vetores podem ser usados na aritmética o ) comum. Próxima: Personagem vetores . R permite a manipulação de quantidades de lógica. Note no entanto que T e F são apenas as variáveis que são definidas para TRUE e FALSE . e NA (para "não disponível". A função is.rep (x. Em geral. Além disso. Quando um elemento ou o valor é "não disponível" ou um "valor faltando" no sentido estatístico.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-.. por exemplo. c1 | c2 e) é a sua união (" u". Precedente: vetores lógicos . Seguinte: Os valores em falta .. e !c1 é a negação de c1 . Precedente: regular gerar seqüências . veja na próxima subseção. por =. A forma mais simples é > <S5 . não está disponível. os componentes de um vetor não pode ser completamente conhecida. mas não são palavras reservadas e.Uma Introdução ao R http://translate. FALSE se tornando 0 e TRUE se tornar 1 .5. 2.

Seguinte: Índice de vetores . is. 14 de 99 25/02/2011 10:36 . Outras seqüências de escape são úteis \n nova linha. o que muda é a cadeia. da mesma forma que seriam se fossem impressas. isto é.6 Personagem vetores Personagem quantidades e vetores de caracteres são utilizados freqüentemente em R. mas são impressos usando aspas duplas (ou às vezes sem as aspas). mas um marcador para uma quantidade que não está disponível. Os argumentos são separados por padrão no resultado por um único caractere em branco. "Y"). backspace-ver? Cotações para uma lista completa. eles são indicados por uma seqüência de caracteres delimitados pelo caractere aspas duplas. por exemplo. Note que existe um segundo tipo de "desaparecidos" os valores que são produzidos por computação numérica. Em resumo. exemplos de uso vão surgir com frequência. Eles usam seqüências de escape estilo-C.na(xx) é TRUE tanto para NA e NaN valores. às vezes impresso como <NA> vetores de caracteres quando são impressas sem aspas. <ind . possivelmente vazio. a chamada Not a Number. NaN . Os valores em falta são. setembro = "") faz labs para o vetor de caracteres c ("X1". "Y8". assim c("X". Anterior: Os valores em falta . Por exemplo > <Laboratórios . dado entre os argumentos são coagidos a cadeias de caracteres no modo evidente. "X9".. is. "New iteration results" .nan(xx) só é TRUE para NaN s. "Y4". Para diferenciá-las. Exemplos são > 0 / 0 ou > Inf . NA). "X3". O paste() função recebe um número arbitrário de argumentos e concatena-los um a um em cadeias de caracteres.na (z) Observe que a expressão lógica x == NA é muito diferente de is. sep= string.googleusercontent. "Y6".Inf que ambos dão NaN desde que o resultado não pode ser definido de forma sensata. 1:10. mas isso pode ser alterado pelo parâmetro nomeado. "Y10") Note particularmente que a reciclagem de listas curtas acontece aqui também.. "x-values" . indecidível. guia e \b . As cadeias de caracteres são digitados ou correspondência (double " ) ou simples ( ' ) aspas. etiquetas parcela.pasta (c ("X". "Y2". Up: Simple números manipulações e vetores 2. 8 "Y") é repetido cinco vezes para igualar a seqüência de 1:10 . > Z <. Assim x == NA é um vetor de mesmo comprimento que x todos cujos valores são NA .com/translate_c?hl=pt-BR&ie=UTF-. valores. usando \ como caracter de escape. Qualquer número. "X5".na(x) desde NA não é realmente um valor.is. \t . e dentro de aspas duplas " está inscrita como \" . assim \\ é entrou e impressos como \\ . "X7". como a expressão lógica em si é incompleta e. portanto.Uma Introdução ao R http://translate. por exemplo. Personagem vetores podem ser concatenados em um vetor pelo c() função. Sempre que necessário.c (1:3.

Um vetor de quantidades positivas integral. um sub-vetor do vetor de nomes podem ser utilizados da mesma forma como os rótulos positivos integral no item 2 mais acima.2. Um vetor de quantidades negativas integral.1). o índice do vetor deve ser do mesmo comprimento que o vetor a partir da qual os elementos devem ser selecionados.. "laranja")] frutas 15 de 99 25/02/2011 10:36 . <> Fruta .x [. 3. y será menor que x .2. "x" repetido quatro vezes. Um vetor lógico.na (x)) & x> 0] -> z cria um objeto z e lugares em que os valores do vetor x+1 para o qual o valor correspondente em x era ao mesmo tempo não falta e positiva. "y". 4. Por exemplo <> Y . Up: manipulações simples números e vetores Índice de 2.com/translate_c?hl=pt-BR&ie=UTF-. eo resultado é do mesmo comprimento que o vetor de índice. "banana". Esta possibilidade só se aplica quando um objeto tem um names de atributo para identificar seus componentes.x [! Is. na mesma ordem do. Neste caso.c (5. . 10. 2. seleção e modificação de subconjuntos de um conjunto de dados Subconjuntos de elementos de um vetor pode ser selecionado por meio do acréscimo do nome do vetor um vetor de índice entre colchetes. Neste caso. Por exemplo. "maçã".(1:5)] dá y todos.c ("laranja". Um vetor de seqüências de caracteres. Esse índice vetor uma especifica os valores a serem excluídos e não incluídos.na (x)] cria (ou recria) um objeto y que conterá os valores em falta. Mais geral.. não de x . Valores correspondentes a TRUE no vetor de índice são selecionados e os correspondentes à FALSE são omitidos. Também > (X +1) [(! Is. length(x) }. 20) > Nomes (fruta) <.7 vetores. os tempos = 4)] (Uma coisa improvável certo a fazer) produz um vetor de caracteres de tamanho 16 que consiste em "x". mas os cinco primeiros elementos de x . Neste caso. "y") [rep (c (1. "pêssego") > <Almoço . anterior: Personagem vetores . Também > C ("x". Os elementos correspondentes do vetor são selecionadas e concatenadas. nessa ordem. os valores no vetor de índice deve estar no conjunto {1. Seguinte: Outros tipos de objetos . no resultado...Uma Introdução ao R http://translate. vetores Esse índice pode ser qualquer um dos quatro tipos distintos.googleusercontent. Note que se x tem valores em falta. O vetor de índice pode ser de qualquer tamanho. "y". qualquer expressão que equivale a um vetor pode ter subconjuntos dos seus elementos igualmente selecionadas anexando um vetor de índice entre colchetes imediatamente após a expressão. 1.. Assim <> Y . 2. 1.[c ("maçã". x[6] é o sexto componente de x e > X [01:10] seleciona os 10 primeiros elementos de x (assumindo que length(x) não é inferior a 10).

como veremos mais tarde. que vamos encontrar mais formalmente nas seções posteriores. Muitas experiências são mais bem descrito por quadros de dados: os tratamentos são categóricos. Precedente: números de simples manipulações e vetores . Isso fornece uma maneira simples e conveniente para estender R. na qual as colunas podem ser de diferentes tipos. Por exemplo > X [is. Up: Simple números manipulações e vetores 2.com/translate_c?hl=pt-BR&ie=UTF-. Veja listas . A vantagem é que os nomes alfanuméricos são muitas vezes mais fácil de lembrar que os índices numéricos.. Uma expressão indexada também pode aparecer no fim de recepção de uma cessão. e muitas vezes são eles mesmos vetores ou listas. seus modos e atributos O modo de atributos intrínsecos e comprimento A mudança no comprimento de um objeto Obter e definir atributos A classe de um objeto 16 de 99 25/02/2011 10:36 . quadros de dados são.0 substitui os valores em falta em x por zeros e > Y [y <0] <--y [y <0] tem o mesmo efeito que > Y <. Na verdade. funções são objetos em R que pode ser armazenado em espaço de trabalho do projeto. Veja escrever suas próprias funções . matrizes ou.8 Outros tipos de objetos Vetores são o tipo mais importante do objeto em R. As listas oferecem um modo conveniente para retornar os resultados de um cálculo estatístico. Veja Fatores . Seguinte: Fatores .Uma Introdução ao R http://translate. e no caso de um vetor de índice lógico que deve voltar a ser o mesmo comprimento que o vetor é a indexação. mas existem muitas outras.googleusercontent. O vetor atribuído deve corresponder ao tamanho do vetor de índice. Esta opção é particularmente útil em conexão com os quadros de dados. Pense de quadros de dados como matrizes «dados» com uma linha por unidade de observação.na (x)] <. mas com (possivelmente) as duas variáveis numéricas e categóricas. caso em que a operação de atribuição é realizada apenas sobre os elementos do vetor. Veja quadros de dados . fatores fornecem maneiras compacto para manipular os dados categóricos. listas são uma forma geral de vetor no qual os vários elementos não precisam ser do mesmo tipo. mas a resposta é numérica. eles são vetores que podem ser indexados por dois ou mais índices e será impresso de maneira especial. Veja matrizes e matrizes . mais geralmente arrays são multi-dimensional de vetores de generalizações. A expressão deve ser da forma vector[ index_vector ] como tendo uma expressão arbitrária no lugar do nome do vetor não faz muito sentido aqui.abs (y) Anterior: Índice de vetores . como as estruturas da matriz. Up: Top 3 Objetos..

. (A aparente única excepção a esta regra é a "especial" o valor listado como NA para as quantidades não estão disponíveis. Por exemplo.. que são de modo lista. R serve para mudanças de modo quase em qualquer lugar que poderia ser considerado razoável para o fazer. complexo. Precedente: Objetos . Up: Objetos 3. (e algumas em que não possa ser). Pelo modo de um objeto que significa que o tipo básico de seus componentes fundamentais. 17 de 99 25/02/2011 10:36 .00:09 poderíamos colocar dígitos> <.googleusercontent. quer lógico. algo () para qualquer coerção de um modo para outro. As funções mode( objeto ) e length( objeto ) pode ser usada para descobrir o modo e tempo de qualquer estrutura definida 10 . numérica 9 . que serão discutidos em detalhe mais tarde. com > Z <. Por exemplo. reconstrói o vetor numérico novamente: > D <. então em uma expressão mode(z) é a seqüência de caracteres "complex" e length(z) é 100 . vetores de valores lógicos e vectores de cadeias de caracteres. "2". consulte Como obter e definir atributos . Outras propriedades de um objeto são normalmente prestados por attributes( objeto ) .integer (dígitos) Agora d e z são os mesmos. exceto indiretamente quando discutimos fórmulas usadas com modelagem em R. "9") . Este é um caso especial de uma "propriedade" de um objeto. lógica e matérias-primas. Expressões como objetos fazem parte avançada de R que não serão discutidos neste guia. Note-se que um vetor pode ser vazio e ainda ter um modo. . Exemplos são os vetores de valores numéricos (real) ou complexos. ou para investir um objeto com algum outro atributo que não pode já possuir. O recursiva outras estruturas são os de função do modo de expressão. Devido a isso.1 atributos intrínsecos: modo e tempo As entidades R opera em são tecnicamente conhecidos como objetos. ou modo. 11 Existe uma grande coleção de funções da forma as.. natureza.as. Seguinte: A mudança no comprimento de um objeto . individualmente. Assim. a seqüência de vetores de caracteres vazia é listada como character(0) eo vetor numérica vazia como numeric(0) . numérico. O leitor deve consultar os arquivos de ajuda diferentes para se familiarizar com eles. Vetores devem ter seus valores todos do mesmo modo. As funções são os objetos que fazem parte do sistema R junto com o usuário similar funções escritas.. Listas são conhecidas como "recursivo" ao invés de estruturas atômicas desde que seus componentes possam ser eles próprios listas em seu próprio direito. Estes são conhecidos como "atômico" estruturas desde os seus componentes são todos do mesmo tipo. pode ser de qualquer modo.com/translate_c?hl=pt-BR&ie=UTF-.character (z) após o qual digits é o vetor de caracteres c("0". R também opera em objetos listas de chamada. o modo e tempo são também chamados de "atributos intrínsecos" de um objeto. se z é um vetor complexo de comprimento 100. qualquer dado vetor deve ser inequívoca. A coerção mais ou mudança de modo.Uma Introdução ao R http://translate. mas na verdade existem vários tipos de NA ). Por exemplo. "1". Outra propriedade de cada objeto é o seu comprimento. Estas são seqüências ordenadas de objetos que.as.. ou cru. de caráter complexo. ou seja.

para associar a criação de uma data ou um operador com um objeto R. Anterior: O modo de atributos intrínsecos e comprimento . (os dois primeiros componentes. Alguns cuidados devem ser tomados quando atribuir ou excluir atributos pois eles são uma parte integrante do sistema de objetos usados em R. novos componentes podem ser adicionados a ele. por exemplo. Isso se aplica a qualquer estrutura de todos. é muito importante. Up: Objetos 3. dando-lhe um valor de índice fora do intervalo anterior. foi criado. se alpha é um objeto de comprimento 10. e assim por diante.com/translate_c?hl=pt-BR&ie=UTF-..Uma Introdução ao R http://translate.3 obter e definir atributos A função de attributes( objeto ) retorna uma lista de todos os não-atributos intrínsecos atualmente definidas para esse objeto. A função attr( objeto .numérico () faz e uma estrutura de vetor vazio de modo numérico. Quando ele é usado no lado esquerdo de uma atribuição que pode ser usado para associar um novo atributo com o objeto ou alterar um já existente. 18 de 99 25/02/2011 10:36 .) Inversamente para truncar o tamanho de um objeto requer apenas uma atribuição para fazê-lo. (Os índices de idade não são mantidas. por exemplo. (Veja o scan () função . é claro. no scan() função para a entrada. Up: Objetos 3. O conceito. Este ajuste automático do comprimento de um objeto é usado com freqüência. Do mesmo modo character() é um vetor de caracteres vazia. Anterior: Mudando o comprimento de um objeto . Assim > E [3] <. como se fosse um-por-10 da matriz 10. Depois que um objeto de qualquer tamanho. Seguinte: A classe de um objeto . exceto em circunstâncias muito especial quando algum novo atributo está sendo criado para algum propósito particular.c (10. Por exemplo > E <. Por exemplo > Attr (z. simplesmente.3 e vetores pode ser estendido (por valores em falta). Seguinte: Como obter e definir atributos .2 Alterando o comprimento de um objeto Um objeto "vazio" pode ainda ter um modo.googleusercontent. que são neste momento os dois NA ). da mesma forma.. "dim") <. entretanto. Essas funções são raramente utilizadas. mesmo com o índice. desde o modo do componente adicional (s) concorda com o modo do objeto em primeiro lugar. > <.Alfa alfa [2 * 01:05] torna um objeto de comprimento 5 que compreende apenas os componentes antigos. Portanto.17 faz agora e um vetor de comprimento 3. nome ) pode ser usado para selecionar um atributo específico. > Comprimento (alfa) <.10) R permite tratar z .) Podemos então manter apenas os três primeiros valores.

mas apenas momentaneamente. "sa". "NSW". relatado pela função de class . "tas". "Vic". Por exemplo. "logical" . se um objeto tem classe "data. "NSW". enquanto unclass> (Inverno) irá imprimi-lo como uma lista comum. "qld". "wa". "NSW". "qld". "factor" e "data.frame" . Somente em situações especiais. mas "matrix" . use a função unclass() .1 Um exemplo específico Suponha.com/translate_c?hl=pt-BR&ie=UTF-. "Vic". "NSW". por exemplo. Seguinte: matrizes e matrizes . e outros chamados funções genéricas como o summary() vai reagir a isso como um argumento de uma forma sensível a sua classe. Enquanto o real "aplicação" de fatores é com as fórmulas do modelo (ver Contrastes ). "acto". mas é quando você está aprendendo a entrar em acordo com a idéia de classe e funções genéricas. Precedente: Objetos . "character" ou "list" .. 4. "Vic". ele será impresso em uma determinada maneira. funções genéricas e as aulas serão discutidas mais adiante na orientação a objeto . em seguida. "NSW". "qld". Por exemplo. nós aqui olhar para um exemplo específico. classificado" significa classificados em ordem alfabética. em vez que você precisa para usar este recurso. "NSW". que é um pouco como uma matriz. Inverno> será impresso em formulário de dados do quadro. "wa". "sa".4 A classe de um objeto Todos os objetos em P tem uma classe. por exemplo "numeric" . conhecida como a classe do objeto é usado para permitir um estilo de objeto orientado 12 de programação em R. "Qld".googleusercontent.c ("tas". "acto") Observe que no caso de um vetor de caracteres ".factor (estado) 19 de 99 25/02/2011 10:36 . temos uma amostra de 30 auditores fiscais de todos os estados e territórios da Austrália 13 e seu estado de origem individual é especificado por um vetor de caracteres de mnemônicos Estado como <> Estado .Uma Introdução ao R http://translate. "Vic".. "Sa". R fornece tanto desordenada e fatores de ordem. Para vetores simples. este é apenas o modo. Anterior: Introdução e definição de atributos Up:. Objetos 3. "array" . "Vic". "NT". Um atributo especial. Um fator é igualmente criado usando o factor() função: > <Statef . "Sa". "wa". Up: Top 4 fatores ordenadas e desordenadas Um fator é um vetor de objeto usado para especificar uma classificação discreta (agrupamento) dos componentes de outros vetores de mesmo comprimento. Para remover temporariamente os efeitos da classe. "wa".frame" são outros valores possíveis.frame" . a plot() função irá exibi-lo graficamente em uma determinada maneira. "NT". "qld". se winter tem a classe "data.

60.5 5.250 A função tapply() é usada para aplicar uma função.1061 2. 58. Depois desta atribuição.500 57.000 60.500 56. 48. statef. 64.500 53. O resultado é uma estrutura do mesmo comprimento que os níveis de atributo do elemento que contém os resultados. 61.7386 0. Para isso. O leitor deve consultar o documento de ajuda para mais detalhes. 49. 49. aqui statef 14 . precisamos escrever uma função de R para calcular o erro padrão para qualquer vector dado. 62.3102 4. O print() função manipula fatores um pouco diferente de outros objetos: statef> [1] sa tas qld nsw nsw wa wa nt qld vic vic nsw qld qld sa [16] tas sa nt wa vic qld nsw nsw wa nsw ato sa ato Vic Níveis: nt nsw ato qld tas sa wa vic Para descobrir os níveis de um fator a função de levels() pode ser usado..244 2. 54.Tapply (rendas. aqui incomes . 59. 59. 46.c (60. 52. Up: Fatores 4. statef stderr) e os valores calculados são então incster> ato sa nt nsw qld tas wa vic 1. para cada grupo de componentes do primeiro argumento. tal função é muito simples de uma linha. aqui mean() . como se fossem as estruturas do vetor separados . 69. 65. 56.600 55. Como não há uma função embutida var() para calcular a variância da amostra.googleusercontent. 70. e neste caso era desnecessária.function (x) sqrt (var (x) / comprimento (x)) (Funções de escrita será considerada mais tarde. "nsw" nt "qld" sa "" tas "vic" wa " O Tapply função () e matrizes irregulares fatores ordenada Seguinte: fatores ordenada . Precedente: Fatores .com/translate_c?hl=pt-BR&ie=UTF-. visto que R tem também uma função embutida sd() ).2 A função tapply() e matrizes irregulares Para continuar o exemplo anterior. em escrever suas próprias funções .Uma Introdução ao R http://translate. indicada pelo serviço: > <Stderr . 49.5 4. 40. 41. 46. 43) Para calcular a média da amostra de renda para cada estado agora podemos usar a função especial tapply() : > Incmeans <. > Níveis (statef) [1] "acto".6575 20 de 99 25/02/2011 10:36 .Tapply (rendas. média) dando um vetor de meios com os componentes marcados pelos níveis ato sa nt nsw qld tas wa vic 44. 61. suponha que temos os rendimentos dos auditores fiscais num outro vector (em unidades suficientemente grande de dinheiro) <> Renda . os erros-padrão são calculados por <Incster> .000 52. definidos pelos níveis do segundo componente. 42. 61. 51. 61.5 4. Suponha ainda que precisávamos para calcular o desvio padrão da renda do estado significa.. 58.333 55. 48.

Quando os tamanhos das subclasses são todos os indexação o mesmo pode ser feito de modo implícito e muito mais eficiente. R permite instalações simples para a criação e manipulação de matrizes.. Precedente: Fatores . O valor é um vetor de resultados da função. A função é aplicada a cada um desses grupos individualmente. Seguinte: Listas e quadros de dados . Os valores do vetor são coletados em grupos. No entanto. A dimensão do vetor é um vetor de inteiros não-negativos. uma vez que os tamanhos das subclasses são possivelmente irregular. Up: matrizes e matrizes 5. poderíamos querer dividir os contabilistas fiscais por estado e sexo. ou na ordem em que foram especificados para factor se eles fossem especificados explicitamente. e em particular o caso especial de matrizes. Up: Fatores 4.3 fatores ordenada Os níveis dos fatores são armazenados em ordem alfabética. mas o contraste gerado por eles no ajuste de modelos lineares são diferentes. marcado pela levels atributo do fator. como podemos ver na próxima seção.Uma Introdução ao R http://translate. Por exemplo. você pode importar para encontrar os habituais limites de confiança de 95% para a média no estado de rendimentos.googleusercontent. Como um exercício. neste caso. simples (apenas um fator) que acontece pode ser pensado como se segue. Se o seu comprimento é k. A combinação de um vetor e um fator de rotulagem é um exemplo de que às vezes é chamada de matriz irregular. O ordered() função cria tais fatores ordenados mas de resto é idêntico ao factor .com/translate_c?hl=pt-BR&ie=UTF-. (Você também pode investigar instalações de P para os testes-t). então a 21 de 99 25/02/2011 10:36 . Para a maioria dos efeitos que a única diferença entre os fatores de ordenados e não ordenados é que os primeiros são impressos mostrando a ordem dos níveis. Para fazer isso você poderia usar tapply() mais uma vez com o length() função para localizar os tamanhos de amostra e do qt() função para localizar os pontos de percentagem do adequado t-distribuições. Precedente: matrizes e matrizes . Up: Top 5 matrizes e matrizes Matrizes indexação de matriz Índice de matrizes A função Array () O produto externo das duas matrizes Generalizado transposição de uma matriz Facilidades Matrix Formando matrizes particionadas A função de concatenação c () com arrays tabelas de freqüência de fatores Em seguida: Matriz de indexação . por exemplo numérico.1 Arrays Uma matriz pode ser considerada como uma coleção multiplicar subscrita de entradas de dados. Às vezes os níveis terão uma ordem natural que queremos gravar e queremos que a nossa análise estatística para fazer uso. Anterior: A função Tapply () e matrizes irregulares . A função tapply() também pode ser usado para tratar mais complicado indexação de um vetor por várias categorias. correspondentes às entradas distintas no fator..

1.. a[2.100) lhe confere o atributo dim que permite que ele seja tratado como um "3 by 5 por 100 matriz. Anterior: Matrizes . Continuando o exemplo anterior..1]. que é "grande encomenda de coluna". A atribuição > Dim (z) <. como veremos em A matriz () função . que é o mesmo que omitir a totalmente subscritos e usar a só. uma matriz é um array de 2 dimensões.] representa a matriz inteira. Os valores no vetor de dados fornecem os valores da matriz na mesma ordem em que iria ocorrer em Fortran. então há 3 * 4 * 2 = 24 entradas em a vetor de dados e os mantém na ordem a[1. Seguinte: Índice de matrizes . Além disso. a[2. Mais genericamente. neste caso o vetor de dimensão é ignorada. Por exemplo. se o único índice não é um vetor. se um nome de matriz é dado com apenas um índice ou um vetor de índice. Outras funções.. Para qualquer matriz.Uma Introdução ao R http://translate. Um vetor pode ser usado por R como uma matriz somente se ele tiver um vetor de dimensão como o seu atributo dim. com o primeiro subscrito mais rápidos e mais lentos subscrito passado.2]) nessa ordem. um [2. dando uma seqüência de vetores de índice. a [2. por exemplo..2 a indexação de matriz.1. se qualquer posição do índice é dado um vetor de índice de vazios. . no entanto.2].2].1]. Up: matrizes e matrizes 22 de 99 25/02/2011 10:36 . Matrizes podem ser unidimensionais: matrizes deste tipo são normalmente tratados da mesma forma como vetores (incluindo a imprimir).1].1]. em seguida. diz a . se o vetor de dimensão para uma matriz.2]. é c(3. a [2. toda a gama de subscrição que for tomada. Este não é o caso. no entanto.4.1]. em substituição de índices. a [2..2]. por exemplo. o vetor de dimensão pode ser referenciado explicitamente como dim(Z) (em ambos os lados de uma atribuição).1.4.5. como estamos proximos discutir. Subseções de uma matriz Os elementos individuais de uma matriz pode ser referenciado por dar o nome da matriz seguido pelos subscritos entre colchetes. a[3.. a [2. digamos Z . matriz é k-dimensional. As dimensões são indexados a partir de um até os valores indicados no vetor de dimensão. tais como matrix() e array() estão disponíveis para simples e mais natural atribuições de quem. Índice de matrizes A função Array () Seguinte: A função Array () . mas também uma matriz.. em seguida.com/translate_c?hl=pt-BR&ie=UTF-.2] .2) eo vetor de dados contendo os valores c (a [2.2. mas as exceções podem causar confusão. a [2. a [2.4.] é um 4 * 2 matriz com a dimensão do vetor c(4. os valores correspondentes do vetor de dados só são utilizadas.1].c (3. a[2. separados por vírgulas. z é um vetor de 1500 elementos.4. a[. anterior: a indexação de matriz .2. Suponha. Up: matrizes e matrizes 5. as subseções de uma matriz pode ser especificado.googleusercontent.3.2) .3.1.4.

[3]. N dizer.matriz (c (1:3. suponha que queiramos gerar uma situação sem redução) projeto (matriz para um delineamento em blocos definidos por fatores blocks ( b níveis) e varieties ( v níveis).1 > XV [iv] <. XV) Para construir a matriz de incidência..3 matrizes Índice Bem como um vetor de índice em qualquer posição subscrito. Um exemplo da matriz torna o processo claro. ou extrair uma coleção irregular como um vetor. NA e valores de zero são permitidos: linhas no índice de matriz contendo um zero são ignoradas. Os índices negativos não são permitidos em matrizes índice.cbind (Xb. Neste caso. c = dim (4. n. [2] [1]. temos uma matriz de 4 por 5 X e queremos fazer o seguinte: Extrair elementos X[1. e as linhas que contêm um NA produzir um NA no resultado. 2 2 [3]. [2]. 4 8 12 16 20 > 4 por 5. Nós poderíamos proceder da seguinte forma: > Xb <. nós poderíamos usar > N <. As entradas no índice da matriz são os índices de linha e coluna para a matriz duplamente indexados. XV) No entanto. uma maneira mais simples direta de produzir essa matriz é a utilização de table() : 23 de 99 25/02/2011 10:36 . X[2. b) > Xv <. [2]..matriz (1:20. um índice da matriz pode ser dada constituído por duas colunas e tantas linhas. e Substituir essas entradas na matriz X por zeros. > X <. 2 0 10 14 18 [3]. c = dim (3. Como um exemplo menos trivial. [5] [1].matriz (0. uma matriz pode ser usada com um único índice da matriz seja para atribuir um vetor de quantidades para uma coleção irregular de elementos do array. . por exemplo. [3].cbind (1: n. 1 5 0 13 17 [2]. 0 7 11 15 19 [4].2)) > I # i é uma matriz 3 por 2 índice. [4]. n.cbind (1: n. Suponha ainda existem n parcelas no experimento. como no exemplo a seguir.Uma Introdução ao R http://translate.3:1). [1]. 5. Suponha. [4].5)) # Gera uma matriz de > X .1] como uma estrutura de vetor. blocos) <> IV . 3 7 11 15 19 [4]. variedades) > Xb [ib] <.com/translate_c?hl=pt-BR&ie=UTF-.2] e X[3. > X . como desejado.3] .googleusercontent. [5] [1]. 1 3 [2].crossprod (Xb. [1]. precisamos de uma matriz de 3 por 2 subscrito. 4 8 12 16 20 > I <.0 # Substitua esses elementos zeros. 3 1 > X [i] # Extrai os elementos [1] 9 6 3 > X [i] <. [1].1 > X <. v) > <Ib .matriz (0. No caso de uma matriz duplamente indexados. 1 5 9 13 17 [2] 2 6 10 14 18 [3].

e isso se torna o vetor de dimensão do resultado.4. Da experiência que temos encontrado o seguinte para ser um guia confiável.2 * A * B + C + 1 faz D uma matriz semelhante com o seu vetor de dados sendo o resultado do elementode-operações de determinado elemento. Portanto.googleusercontent. Up: matriz A () função 5. os números. Seguinte: O produto externo das duas matrizes . Matrizes podem ser usadas em expressões aritméticas eo resultado é um conjunto formado por operações elemento por elemento do vetor de dados. dim (Z) <.h. então o comando > Z <. se A . No entanto. um caráter lógico ou matriz) fornecidos como uma matriz é tratada como um vetor de indexação.c(3.matriz (h. c = dim (3. os vetores podem ser construídos a partir de vetores da array função. Como um exemplo extremo. mas dim(h) <.4. e Z[] com um índice vazio ou Z com não subscrito representa a matriz inteira como uma matriz.2) e Z[1:24] representa o vetor de dados como era no h . A regra da reciclagem Precedente: matriz A () função .2)) usaria h criar 3 por 4 a 2 na série Z .matriz (data_vector. Up: matrizes e matrizes 5. B e C são matrizes semelhantes.4.2) seria um sinal de erro sobre o descasamento comprimento. > N <. dim_vector) Por exemplo. os seus valores são reciclados a partir do início de novo para fazê-lo até o tamanho 24 (ver A regra da reciclagem ). a regra precisa quanto à matriz mista e os cálculos do vetor tem que ser considerado um pouco mais de cuidado. Neste ponto. c (3.tabela (blocos.2)) torna Z uma matriz de zeros.c (3. A expressão é digitalizado a partir da esquerda para a direita. Anterior: Índice de matrizes . mas comuns > Z <. O dim atributos de operandos geralmente precisa ser o mesmo. que tem a forma > Z <.array (0.Uma Introdução ao R http://translate.com/translate_c?hl=pt-BR&ie=UTF-. A regra da reciclagem A regra precisa afetando elemento por elemento misto cálculos com vetores e matrizes é algo peculiar e difícil de encontrar nas referências.1 vetores e aritmética mista matriz.4.. se o vetor h tem 24 ou menos. o resultado é o mesmo que > Z <. Se o tamanho h é exatamente 24. então > D <. Qualquer operandos vetoriais curto são estendidos através da reciclagem de seus valores 24 de 99 25/02/2011 10:36 .4. se h for menor que 24. variedades) Índice de matrizes deve ser numérica: qualquer outra forma de matriz (por exemplo.4..4 O array() função Bem como dar uma estrutura de um vetor dim atributo.2) No entanto. dim(Z) representa o vetor de dimensão c(3.

que é um dígito .5 O produto exterior de dois vetores Uma operação importante em matrizes é o produto externo. type = "h". ylab = "Freqüência") Observe a coerção dos names atributo da tabela de freqüência para numérico. 1). "-")) > Plot (as.Uma Introdução ao R http://translate. não-comutativa. se cada dígito é escolhido de forma independente e uniformemente ao acaso. Por exemplo. 1. naturalmente. b.numeric (nomes (fr)). Se as estruturas de matriz estão presentes e nenhum erro ou a coação para vetor foi precipitada. até que eles correspondam ao tamanho de qualquer outros operandos. Uma boa forma de fazer isso usa o outer() função duas vezes: > D <. as matrizes devem ter todos a mesma dim atributo ou um erro.com/translate_c?hl=pt-BR&ie=UTF-. 25 de 99 25/02/2011 10:36 . Se a e b são duas matrizes numéricas.exterior (0:09. y) = cos (y) / (1 + x ^ 2) sobre uma grade regular de valores com x-e y-coordenadas definida pelos vetores R x e y . f) Em particular.. . seu produto externo é uma matriz cuja dimensão do vetor é obtido concatenando os dois vetores de dimensão (a ordem é importante). a fim de recuperar o intervalo de valores determinantes.function (x.exterior (x. formando todos os produtos possíveis de elementos do vetor de dados a com os de b . onde cada entrada é um inteiro não-negativo no intervalo de 0. o produto externo de dois vetores normais é uma matriz duplamente subscrito (que é uma matriz de classificação.exterior (a. podemos proceder da seguinte forma: > F <. 0:09) > <Fr . Um exemplo: Determinantes de 2 por 2 matrizes de um dígito Como um exemplo. c. d. b. Enquanto curto vetores e matrizes somente são encontradas. Anterior: A função Array () .tabela (exterior (d. Qualquer vector operando mais de um operando matricial ou matriz gera um erro. Up: matrizes e matrizes 5. Isto equivale a encontrar a distribuição de probabilidade de o fator determinante.. 9. Definindo suas próprias funções R será considerado ainda em escrever suas próprias funções . e cujos dados vetoriais tenho. considere os determinantes de matrizes 2 por 2 [a. Observe que o operador produto externo é. O produto externo é formado pelo operador especial %o% : <Ab> .bc. XLAB = "determinantes". mas bonito artificial. y) cos (y) / (1 + x ^ 2) > Z <.googleusercontent. de todas as matrizes possível desta forma e representa a freqüência com que cada valor ocorre como uma trama de alta densidade.a% b% o Uma alternativa é > <Ab . O óbvio "caminho" de fazer esse problema com o for loops. respectivamente .. no máximo. fr. ad . Seguinte: Generalized transposição de uma matriz ... y. d]. se quisermos avaliar a função f (x. "*") A função de multiplicação pode ser substituída por uma função arbitrária de duas variáveis. o resultado é uma estrutura matricial com o mercado comum dim atributo de sua matriz operandos. O problema é encontrar os determinantes.

se A é uma matriz (ou seja.7 instalações Matrix Como mencionado acima.googleusercontent. Up: matrizes e matrizes 5. onde k é o número de subscritos em a . (embora nem sempre isso é possível de forma inequívoca.6 transposição generalizada de uma matriz A função aperm(a. C (2. No entanto. O argumento perm deve ser uma permutação dos inteiros {1. é um caso tão importante e específico que necessita de uma discussão em separado. Up: instalações Matrix 5. Um n por 1 ou por uma matriz n pode. respectivamente. De fato.aperm (A.. para ser discutido em Loops e execução condicional . k}. R contém muitos operadores e funções que estão disponíveis apenas para as matrizes.7.com/translate_c?hl=pt-BR&ie=UTF-. Precedente: Generalized transposição de uma matriz .. como descrito acima. As funções nrow(A) e ncol(A) indicar o número de linhas e colunas na matriz A . A e B são matrizes quadradas do mesmo tamanho.. a . Up: matrizes e matrizes 5. A maneira mais fácil pensar desta operação é como uma generalização da transposição para as matrizes.t(A) . ser usado como um vetor n-se no contexto como é apropriado. Para este caso específico uma simples função de t() está disponível. é tão ineficaz quanto a ser impraticável.. Multiplicação equações lineares e inversão Autovalores e autovetores decomposição em valores singulares e determinantes Mínimos quadrados montagem ea decomposição QR Seguinte: equações lineares e de inversão . então B dada por > B <. como vemos mais tarde). então poderíamos ter usado B <. Por outro lado.1 A multiplicação de matrizes O operador %*% é usado para multiplicação de matrizes. o que for multiplicatively coerente. naturalmente.Uma Introdução ao R http://translate. se possível. Se. perm) pode ser usado para permutar uma matriz.1)) é apenas a transposição de A . Seguinte: Formação matrizes particionadas . Por exemplo. então > A * B é a matriz de elemento por elemento e produtos > A *%% B 26 de 99 25/02/2011 10:36 . Seguinte: instalações Matrix . por exemplo. . mas com dimensão dada por perm[j] se tornando o novo j ª dimensão. t(X) é a função de transpor a matriz.. Precedente: O exterior do produto de duas matrizes . uma matriz é apenas uma matriz com dois subscritos. uma subscrita matriz duplamente). Precedente: instalações Matriz . os vetores que ocorrem em expressões de multiplicação de matrizes são automaticamente promovidos tanto aos vetores linha ou coluna. O resultado da função é uma matriz do mesmo tamanho que a velho. Também é surpreendente que cerca de 1 em 20 matrizes seja singular.

então diag(k) é a k pelo k matriz identidade! Seguinte: Autovalores e autovetores . é ineficiente e potencialmente instável para calcular x <. onde v é um vetor. mas a operação é mais eficiente. diag(v) . Seguinte: decomposição em valores singulares e determinantes . Note-se que em álgebra linear. O resultado desta função é uma lista de dois componentes chamados values e vectors .solve(A) %*% b em vez de solve(A. Up: instalações Matrix 5. depois de B> <. deve ser calculado por algo como 16 x %*% solve(A.. Se x é um vetor. Esta é a mesma convenção que o utilizado para diag() em MATLAB.7. Numericamente. retornando x (até alguma perda de precisão). A forma quadrática x %*% A^{-1} %*% x . onde M é uma matriz.com/translate_c?hl=pt-BR&ie=UTF-. dá uma matriz diagonal com elementos do vetor como as entradas de diagonal. formalmente x = A^{-1} %*% b .eigen (Sm) atribui essa lista para ev . é considerado como sendo o mesmo que o primeiro.b) . é o produto da matriz.Uma Introdução ao R http://translate. Então ev$val é o vetor de autovalores de Sm e ev$vec é a matriz de autovetores correspondentes. 15 A função crossprod() formas "crossproducts". Quando. A atribuição > <Ev . instalações Matrix 5. onde A^{-1} indica o inverso de A .eigen (Sm) $ valores 27 de 99 25/02/2011 10:36 . Se tivéssemos apenas necessário os autovalores poderíamos ter usado o serviço: evals> <. O significado do diag() depende de seu argumento.googleusercontent.3 Autovalores e autovetores A função eigen(Sm) calcula os autovalores e autovetores de uma matriz simétrica Sm .. Anterior: Multiplicação .x) . que é usado em cálculos multivariada. em seguida. > Resolver (a. Em R. um tanto confusa.A *% x% apenas A e b são dadas. ao invés de calcular a inversa de A . b) resolve o sistema. dá o principal vetor de entradas diagonais de M . y) é o mesmo que t(X) %*% y . o vetor x é a solução desse sistema de equações lineares. Precedente: equações lineares e inversão Up:. Além disso. Por outro lado diag(M) . que pode ser calculado por resolver (A) mas raramente é necessário. Se o segundo argumento para crossprod() for omitido.7.2 equações lineares e inversão Resolução de equações lineares é a inversa da multiplicação de matrizes. >% * X% A *%% x é uma forma quadrática. se k é um valor numérico único. significando que crossprod(X.

4 decomposição em valores singulares e determinantes A função svd(M) tem uma matriz de argumentos arbitrários. Up: Matrix facilities 5. evals agora detém o vetor de autovalores eo segundo componente é descartado.values = TRUE) $ valores Seguinte: Mínimos quadrados montagem ea decomposição QR .) (see Linear models ) to lsfit() for regression modelling. e calcula a decomposição em valores singulares de M . including the sign.função (M) prod (svd (M) $ d) after which we could use absdet() as just another R function. D é realmente voltou como um vetor de elementos da diagonal. muitas vezes com uma variedade de matrizes pode ser definida como uma função de R > <Absdet . com significados evidentes. to calculate the trace of a square matrix. y) gives the results of a least squares fit where y is the vector of observations and X is the design matrix.7. regression diagnostics. y) 28 de 99 25/02/2011 10:36 . Se M é na praça de fato. only. u e v . M . cujo espaço de coluna é o espaço de linha de M e uma matriz diagonal de entradas positivas D tal que M = U %*% D %*% t(V) . and also for the follow-up function ls. com os seus nomes.googleusercontent. Precedente: Autovalores e autovetores . An assignment such as > ans <.7.prod (svd (M) $ d) calcula o valor absoluto do determinante de M . Another closely related function is qr() and its allies.Uma Introdução ao R http://translate. you might like to consider writing a function. [Hint: You will not need to use an explicit loop.com/translate_c?hl=pt-BR&ie=UTF-.. Consider the following assignments > Xplus <. As a further trivial but potentially useful example. Up: instalações Matrix 5.qr.] R has a builtin function det to calculate a determinant. Se este cálculo fosse necessário. Este consiste de uma matriz de colunas ortonormais U com o espaço mesma coluna M .eigen (Sm. Previous: Singular value decomposition and determinants . Para grandes matrizes é melhor evitar a computação autovetores se eles não são necessários ao usar a expressão evals> <. say tr() .5 Least squares fitting and the QR decomposition The function lsfit() returns a list giving results of a least squares fitting procedure. and another. Look again at the diag() function. então. See the help facility for more details. Further note that you almost always will prefer using lm(.diag() for. não é difícil perceber que > AbsdetM <. segundo uma matriz de colunas ortonormais V . Se a expressão > Eigen (Sm) é usado por si só como um comando os dois componentes são impressas.lsfit(X. O resultado da svd(M) é na verdade uma lista de três componentes chamados d .coef(Xplus. to give the sign and modulus (optionally on log scale). Note that a grand mean term is automatically included and need not be included explicitly as a column of X .. among other things. determinant .qr(X) > b <.

In the assignment > X <...googleusercontent.. X1. The official way to coerce an array back to a simple vector object is to use as. The function rbind() does the corresponding operation for rows. in which case they are cyclically extended to match the matrix column size (or the length of the longest vector if no matrices are given). X2) The result of rbind() or cbind() always has matrix status. the projection onto the orthogonal complement in res and the coefficient vector for the projection in b . as will be discussed in Statistical models in R . Previous: Forming partitioned matrices . arg_3 . It is not assumed that X has full column rank. forming the columns. cbind() and rbind() As we have already seen informally. the basic c() function does not.) the arguments to cbind() must be either vectors of any length. This is occasionally useful in its own right. arg_2 .cbind( arg_1 ..fitted(Xplus.qr.cbind(1. > fit <. y) These compute the orthogonal projection of y onto the range of X in fit .. possibly cyclically extended.com/translate_c?hl=pt-BR&ie=UTF-. or row-wise.qr. or matrices with the same column size. with arrays It should be noted that whereas cbind() and rbind() are concatenation functions that respect dim attributes.9 The concatenation function. Although still useful in some contexts. it would now generally be replaced by the statistical models features. that is. arg_2 . This alternative is the older. . b is essentially the result of the MATLAB `backslash' operator. matrices can be built up from other vectors and matrices by the functions cbind() and rbind() . or column-wise.resid(Xplus.. . Roughly cbind() forms matrices by binding together matrices horizontally. low-level way to perform least squares calculations. are of course taken as row vectors. together with an initial column of 1 s we can use > X <. The result is a matrix with the concatenated arguments arg_1 . In this case any vector argument. Suppose X1 and X2 have the same number of rows. Next: The concatenation function c() with arrays .Uma Introdução ao R http://translate. Hence cbind(x) and rbind(x) are possibly the simplest ways explicitly to allow the vector x to be treated as a column or row matrix respectively. Previous: Matrix facilities . To combine these by columns into a matrix X . Redundancies will be discovered and removed as they are found. and rbind() vertically.vector() 29 de 99 25/02/2011 10:36 . Up: Arrays and matrices 5. Up: Arrays and matrices 5. but rather clears numeric objects of all dim and dimnames attributes. Next: Frequency tables from factors . that is the same number of rows. y) > res <. c() .8 Forming partitioned matrices. If some of the arguments to cbind() are vectors they may be shorter than the column size of any matrices present.

vector(X) However a similar result can be achieved by using c() with just one argument..tapply(statef.10 Frequency tables from factors Recall that a factor defines a partition into groups. breaks = 35+10*(0:7))) -> incomef Then to calculate a two-way table of frequencies: > table(incomef. The function table() allows frequency tables to be calculated from equal length factors.com/translate_c?hl=pt-BR&ie=UTF-. Previous: The concatenation function c() with arrays . This simple case is equivalent to. length) Further suppose that incomef is a factor giving a suitably defined “income class” for each entry in the data vector.75] 0 1 0 0 0 0 1 0 Extension to higher-way frequency tables is immediate. > vec <. Up: Arrays and matrices 5. that statef is a factor giving the state code for each entry in a data vector.55] 1 1 1 1 2 0 1 3 (55. The frequencies are ordered and labelled by the levels attribute of the factor. Similarly a pair of factors defines a two way cross classification.. Previous: Lists and data frames .45] 1 1 0 1 0 0 1 0 (45. Up: Lists and data frames 30 de 99 25/02/2011 10:36 .c(X) There are slight differences between the two. but more convenient than. for example with the cut() function: > factor(cut(incomes. the result is a k-way array of frequencies.googleusercontent. Next: Reading data from files .Uma Introdução ao R http://translate. simply for this side-effect: > vec <. but ultimately the choice between them is largely a matter of style (with the former being preferable). > statefr <. Suppose. Previous: Arrays and matrices . If there are k factor arguments. for example.statef) statef incomef act nsw nt qld sa tas vic wa (35.table(statef) gives in statefr a table of frequencies of each state in the sample.65] 0 3 1 3 2 2 2 1 (65. Up: Top 6 Lists and data frames Listas Constructing and modifying lists Data frames Next: Constructing and modifying lists . statef. and so on.as. A atribuição > statefr <.

similarly be given a names attribute also.Uma Introdução ao R http://translate. of course. Components of lists may also be named . The latter is a sublist of the list Lst consisting of the first entry only. then the function length(Lst) gives the number of (top level) components it has. a function. Thus the former is the first object in the list Lst . no. Lst[[2]] . a logical value. This is a very useful convention as it makes it easier to get the right component if you forget the number. Other structures besides lists may. There is no particular need for the components to be of the same mode or type. for example. So in the simple example given above: Lst$name Lst$wife is the same as Lst[[1]] and is the string "Fred" . and so on.1 Lists An R list is an object consisting of an ordered collection of objects known as its components . If it is a named list.7. Next: Data frames . If Lst is a list. a character array.com/translate_c?hl=pt-BR&ie=UTF-. ] ' is a general subscripting operator.. wife="Mary". the names are transferred to the sublist. more conveniently.. or. a matrix. and if it is a named list the name is not included. whereas ' [ .children=3. Lst[[3]] and Lst[[4]] ..list(name="Fred".ages[1] Additionally.googleusercontent. a complex vector. The vector of names is in fact simply an attribute of the list like any other and may be handled as such. child. further. by giving an expression of the form > name $ component_name for the same thing. Previous: Lists . Lst[[x]] It is very important to distinguish Lst[[1]] from Lst[1] . ' [[ .."name". is the same as Lst[[2]] and is the string "Mary" . Lst$child. Thus Lst$coefficients may be minimally specified as Lst$coe and Lst$covariance as Lst$cov . Lst[["name"]] is the same as Lst$name . Thus if Lst is the name of a list with four components. and in this case the component may be referred to either by giving the component name as a character string in place of the number in double square brackets. Up: Lists and data frames 31 de 99 25/02/2011 10:36 .9)) Components are always numbered and may always be referred to as such. Lst[[4]] is a vector subscripted array then Lst[[4]][1] is its first entry. when the name of the component to be extracted is stored in another variable as in > x <. 6.. ]] ' is the operator used to select a single element.ages=c(4. ie. these may be individually referred to as Lst[[1]] . a list could consist of a numeric vector. Here is a simple example of how to make a list: > Lst <.. one can also use the names of the list components in double square brackets. is the same as Lst[[4]][1] and is the number 4 . This is especially useful. and. The names of components may be abbreviated down to the minimum number of letters needed to identify them uniquely. If.

c(list. respectively. (which can be freely chosen). lists. Up: Lists and data frames 6.list(matrix=Mat) Concatenating lists Previous: Constructing and modifying lists ... . . whose components are those of the argument lists joined together in sequence. Previous: Constructing and modifying lists . A data frame may for many purposes be regarded as a matrix with columns possibly of differing modes and attributes. .. like any subscripted object. 6. logicals and factors are included as is.C) Recall that with vector objects as arguments the concatenation function similarly joined together all arguments into a single vector structure. and its rows and columns extracted using matrix indexing conventions. Numeric vectors. or variables. list. .. lists. There are restrictions on lists that may be made into data frames. list. Up: Constructing and modifying lists 6. object_m for the components and giving them names as specified by the argument names. whose levels are the unique values appearing in the vector. the result is an object of mode list also.googleusercontent. and character vectors are coerced to be factors. Por exemplo > Lst[5] <. elements. and matrix structures must all have the same row size . such as dim attributes. > list. Making data frames attach() and detach() Working with data frames Attaching arbitrary lists Managing the search path 32 de 99 25/02/2011 10:36 . factors. can be extended by specifying additional components.3 Data frames A data frame is a list with class "data. character. Vector structures appearing as variables of the data frame must all have the same length .1 Concatenating lists When the concatenation function c() is given list arguments. or other data frames. Matrices.A. name_m = object_m ) sets up a list Lst of m components using object_1 . The components used to form the list are copied when forming the new list and the originals are not affected. are discarded. numeric matrices. An assignment of the form > Lst <. namely The components must be vectors (numeric.B.2 Constructing and modifying lists New lists may be formed from existing objects by the function list() .ABC <.com/translate_c?hl=pt-BR&ie=UTF-.. It may be displayed in matrix form. Lists. and data frames provide as many variables to the new data frame as they have columns.. If these names are omitted. In this case all other attributes.2.list( name_1 = object_1 .Uma Introdução ao R http://translate.frame" . the components are numbered only. or logical).

but rather masks it with another variable u in the working directory at position 1 on the search path.frame : > accountants <.3. A useful facility would be somehow to make the components of a list or data frame temporarily visible as variables under their component name. without the need to quote the list name explicitly each time.com/translate_c?hl=pt-BR&ie=UTF-.data. At this point an assignment such as w > u <. You can alter the attached values via assign . v or in position 1 . and what is attached is a copy of the original object. The attach() function takes a `database' such as a list or data frame as its argument. Previous: Data frames . 33 de 99 25/02/2011 10:36 . To detach a data frame.3. for list components is not always very convenient. for example by detach(lentils) or detach("lentils") Note: In R lists and data frames can only be attached at position 2 or above.table() function to read an entire data frame from an external file.googleusercontent. Next: attach() and detach() . lentils$v . Next: Working with data frames . Up: Data frames 6. loot=incomes. v and w would be no longer visible.1 Making data frames Objects satisfying the restrictions placed on the columns (components) of a data frame may be used to form one using the function data. use the function > detach() More precisely.2 attach() and detach() The $ notation. Up: Data frames 6. such as accountants$statef . This is discussed further in Reading data from files . Previous: Making data frames .. this statement detaches from the search path the entity currently at position 2 .v+w does not replace the component u of the data frame. Thus in the present context the variables u . except under the list notation as lentils$u and so on. Entities at positions greater than 2 on the search path can be detached by giving their number to detach .frame() The simplest way to construct a data frame from scratch is to use the read. The attach > attach(lentils) places the data frame in the search path at position 2 . lentils$w .Uma Introdução ao R http://translate.v+w However the new value of component u is not visible until the data frame is detached and attached again.data. u . v and w are available as variables from the data frame in their own right.frame(home=statef. the simplest way is to resort once again to the $ notation: > lentils$u <. but the original list or data frame is unchanged. but it is much safer to always use a name. and provided there are no variables u . To make a permanent change to the data frame itself. Thus suppose lentils is a data frame with three variables lentils$u . shot=incomef) A list whose components conform to the restrictions of a data frame may be coerced into a data frame using the function as..

. but other classes of object as well. by name.Uma Introdução ao R http://translate. In particular any object of mode "list" may be attached in the same way: attach() > attach(any.5 Managing the search path The function search shows the current search path and so is a very useful way to keep track of which data frames and lists (and packages) have been attached and detached. we detach the data frame and confirm it has been removed from the search path. for example.GlobalEnv is the workspace. Previous: Attaching arbitrary lists .GlobalEnv" "Autoloads" "package:base" where .3 Working with data frames A useful convention that allows you to work with many different problems comfortably together in the same working directory is gather together all variables for any well defined and separate problem in a data frame under a suitably informative name. Next: Attaching arbitrary lists . Initially it gives > search() [1] ".old. Up: Data frames 6.4 Attaching arbitrary lists is a generic function that allows not only directories and data frames to be attached to the search path.3.3. all of which have variables named x . Up: Data frames 6. by position number or. Up: Data frames 6.. Finally. when working with a problem attach the appropriate data frame at position 2 . y and z . Previous: Working with data frames .list) Anything that has been attached can be detached by detach . 17 After lentils is attached we have > search() [1] ". and use the working directory at level 1 for operational quantities and temporary variables.googleusercontent. and then detach() . preferably.3. In this way it is quite simple to work with many problems in the same directory.GlobalEnv" "lentils" "Autoloads" "package:base" > ls(2) [1] "u" "v" "w" and as we see ls (or objects ) can be used to examine the contents of any position on the search path.com/translate_c?hl=pt-BR&ie=UTF-. before leaving a problem. Previous: attach() and detach() . add any variables you wish to keep for future reference to the data frame using the $ form of assignment. finally remove all unwanted variables from the working directory and keep it as clean of left-over temporary variables as possible. Next: Managing the search path . > detach("lentils") 34 de 99 25/02/2011 10:36 .

table() function.75 93.table() function To read an entire data frame directly. Previous: Lists and data frames .9 yes . such as file editors or Perl 18 to fit in with the requirements of R. Up: Top 7 Reading data from files Large data objects will usually be read as values from external files rather than entered during an R session at the keyboard.75 128.2 no 04 57.table() function The scan() function Accessing builtin datasets Editing data Next: The scan() function . an entire data frame can be read directly with the read.50 101.8 no 05 59. The first line of the file should have a name for each variable in the data frame. see the R Data Import/Export manual.table() can then be used to read the data frame directly > HousePrice <.0 690 6 8.5 no 03 57. the external file will normally have a special form.read.1 The read.table("houses.0 830 5 6.2 no 02 54.com/translate_c?hl=pt-BR&ie=UTF-. In this 35 de 99 25/02/2011 10:36 . such as Cent..00 111.0 710 5 7. > search() [1] ".googleusercontent. R input facilities are simple and their requirements are fairly strict and even rather inflexible. as factors.0 900 5 1.GlobalEnv" "Autoloads" "package:base" Next: Probability distributions ..50 131. Up: Reading data from files 7.data") Often you will want to omit including the row labels directly and use the default labels.heat 01 52. scan() . Generally this is very simple. By default numeric items (except row labels) are read as numeric variables and non-numeric variables. The function read. This can be changed if necessary. Each additional line of the file has as its first item a row label and the values for each variable. There is also a more primitive input function. There is a clear presumption by the designers of R that you will be able to modify your input files using other tools. For more details on importing data into R and also exporting data. So the first few lines of a file to be read as a data frame might look as follows..Uma Introdução ao R http://translate. that can be called directly.heat in the example. The read. Input file form with names and row labels: Price Floor Area Rooms Age Cent.0 1000 5 4.. this arrangement is presumed to be in force. If variables are to be held mainly in data frames. Previous: Reading data from files . If the file has one fewer item in its first line than in its second. as we strongly suggest they should be.

. The first step is to use scan() to read in the three vectors as a list.2 no 128. byrow=TRUE) There are more elaborate input facilities available and these are detailed in the manuals. Input file form without row labels: Price 52.table("houses.scan("input. is a list whose components are the three vectors read in. that no explicit row labels are given.inp[[3]] More conveniently.com/translate_c?hl=pt-BR&ie=UTF-.2 no 131. as follows > inp <. use assignments like > label <. and hence. case the file may omit the row label column as in the following. list("".0 830 5 6.dat". If the second argument is a single value and not a list.data".0.inp[[1]].inp$y or the list may be attached at position 2 of the search path (see Attaching arbitrary lists ). the dummy list can have named components.Uma Introdução ao R http://translate.75 57. header=TRUE) where the header=TRUE option specifies that the first line is a line of headings. Floor Area Rooms Age Cent. ncol=5.heat 111.matrix(scan("light. held in inp . list(id="". 0). by implication from the form of the file.50 57.inp$id. a single vector is read in.. y=0)) If you wish to access the variables separately they may either be re-assigned to variables in the working frame: > label <.0 900 5 1.00 54. y <.0 1000 5 4.75 ..dat". the first of mode character and the remaining two of mode numeric.. Up: Reading data from files 7.googleusercontent.2 The scan() function Suppose the data vectors are of equal length and are to be read in parallel. in which case the names can be used to access the vectors read in.5 no 101.inp$x. all components of which must be of the same mode as the dummy value. The scan() function Next: Accessing builtin datasets .50 59. Further suppose that there are three vectors. For example > inp <.0 690 6 8.0)) The second argument is a dummy list structure that establishes the mode of the three vectors to be read.table() function .dat". x <. Previous: The read.0 710 5 7. > X <. x=0.9 yes The data frame may then be read as > HousePrice <.inp[[2]]. x <. To separate the data items into three separate vectors.dat .read. The result. 36 de 99 25/02/2011 10:36 . y <.scan("input. and the file is input.8 no 93.

for example data(package="rpart") data(Puromycin. use the package argument. Use > xnew <.edit(xold) .3. Next: Loops and conditional execution . Up: Reading data from files 7.edit(xold) will allow you to edit your data set xold . which is equivalent to xold <.com/translate_c?hl=pt-BR&ie=UTF-.3 Accessing builtin datasets Around 100 datasets are supplied with R (in package datasets ). Previous: The scan() function . O comando > xnew <. 7. Next: Editing data .and two-sample tests 37 de 99 25/02/2011 10:36 . its datasets are automatically included in the search.Uma Introdução ao R http://translate.. However. package="datasets") If a package has been attached by library .0. edit brings up a separate spreadsheet-like environment for editing.4 Editing data When invoked on a data frame or matrix. Up: Top 8 Probability distributions R as a set of statistical tables Examining the distribution of a set of data One. the simplest way is to use fix(xold) . In most cases this will load an R object of the same name. and on completion the changed object is assigned to xnew .edit(data. Up: Reading data from files 7.googleusercontent. This is useful for making small changes once a data set has been read. and others are available in packages (including the recommended packages supplied with R).0 all the datasets supplied with R are available directly by name. many packages still use the earlier convention in which data was also used to load datasets into R.frame()) to enter new data via the spreadsheet interface. in a few cases it loads several objects. User-contributed packages can be a rich source of datasets. for example data(infert) and this can still be used with the standard packages (as in this example). Previous: Reading data from files . However. so see the on-line help for the object to see what to expect. Previous: Accessing builtin datasets .1 Loading data from other R packages To access data from a particular package.. To see the list of datasets currently available use data() As from R version 2. If you want to alter the original dataset xold .

Aqui estão alguns exemplos 38 de 99 25/02/2011 10:36 . lower. ncp chi-squared exp rate exponencial f df1. directly.Uma Introdução ao R http://translate.. This allows. shape2. scale Cauchy chisq df. Distribuição R name argumentos adicionais beta shape1.tail and log.F(t)). the smallest x such that P(X <= x) > q). k hypergeometric hyper lnorm meanlog. ..p xxx (t. log = TRUE) ). n. scale logística negative binomial nbinom size.. max uniforme weibull shape.com/translate_c?hl=pt-BR&ie=UTF-. Functions are provided to evaluate the cumulative distribution function P(X <= x). The p xxx and q xxx functions all have logical arguments lower...googleusercontent. In not quite all cases is the non-centrality parameter ncp currently available: see the on-line help for details. for which it is nn ). H(t) = log(1 .tail = FALSE. ncp Student's t unif min. Up: Probability distributions 8. and to simulate from the distribution.p and the d xxx ones have log . and dmultinom and rmultinom for the multinomial distribution.p = TRUE) or more accurate log-likelihoods (by d xxx (.. scale Weibull wilcox m. eg. sd normal pois lambda Poisson signrank n signed rank t df. ' q ' for the quantile function and ' r ' for simulation ( r andom deviates). by . the probability density function and the quantile function (given q. In addition there are functions ptukey and qtukey for the distribution of the studentized range of samples from a normal distribution. prob binômio cauchy location. getting the cumulative (or “integrated”) hazard function. ' p ' for the CDF. notably SuppDists . Previous: Probability distributions . Next: Examining the distribution of a set of data . Further distributions are available in contributed packages. ncp beta binom size. n Wilcoxon Prefix the name given here by ' d ' for the density. scale gama geom prob geométrico m. prob norm mean. The first argument is x for d xxx . df2. q for p xxx .1 R as a set of statistical tables One convenient use of R is to provide a comprehensive set of statistical tables. p for q xxx and n for r xxx (except for rhyper . log.. ncp F gamma shape. sdlog log-normal logis location. rsignrank and rwilcox ..

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

> ##

2-tailed p-value for t distribution
> 2*pt(-2.43, df = 13) > ## upper 1% point for an F(2, 7) distribution > qf(0.01, 2, 7, lower.tail = FALSE)

See the on-line help on RNG for how random-number generation is done in R. Next: One- and two-sample tests , Previous: R as a set of statistical tables , Up: Probability distributions 8.2 Examining the distribution of a set of data Given a (univariate) set of data we can examine its distribution in a large number of ways. The simplest is to examine the numbers. Two slightly different summaries are given by summary and fivenum and a display of the numbers by stem (a “stem and leaf” plot).
> attach(faithful) > summary(eruptions) Min. 1st Qu. Median Mean 3rd Qu. Máx. 1.600 2.163 4.000 3.488 4.454 5.100 > fivenum(eruptions) [1] 1.6000 2.1585 4.0000 4.4585 5.1000 > stem(eruptions) The decimal point is 1 digit(s) to the left of the | 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 | | | | | | | | | | | | | | | | | | 070355555588 000022233333335577777777888822335777888 00002223378800035778 0002335578023578 00228 23 080 7 2337 250077 0000823577 2333335582225577 0000003357788888002233555577778 03335555778800233333555577778 02222335557780000000023333357778888 0000233357700000023578 00000022335800333 0370

A stem-and-leaf plot is like a histogram, and R has a function hist to plot histograms.
> hist(eruptions) ## make the bins smaller, make a plot of density > hist(eruptions, seq(1.6, 5.2, 0.2), prob=TRUE) > lines(density(eruptions, bw=0.1)) > rug(eruptions) # show the actual data points

More elegant density plots can be made by density , and we added a line produced by density in this example. The bandwidth bw was chosen by trial-and-error as the default gives too much smoothing (it usually does for “interesting” densities). (Better automated methods of bandwidth choice are available, and in this example bw = "SJ" gives a good result.) We can plot the empirical cumulative distribution function by using the function ecdf .
> plot(ecdf(eruptions), do.points=FALSE, verticals=TRUE)

This distribution is obviously far from any standard distribution. How about the right-hand mode,

39 de 99

25/02/2011 10:36

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

say eruptions of longer than 3 minutes? Let us fit a normal distribution and overlay the fitted CDF.
> long <- eruptions[eruptions > 3] > plot(ecdf(long), do.points=FALSE, verticals=TRUE) > x <- seq(3, 5.4, 0.01) > lines(x, pnorm(x, mean=mean(long), sd=sqrt(var(long))), lty=3)

Quantile-quantile (QQ) plots can help us examine this more carefully.
par(pty="s") # arrange for a square figure region qqnorm(long); qqline(long)

which shows a reasonable fit but a shorter right tail than one would expect from a normal distribution. Let us compare this with some simulated data from at distribution
x <- rt(250, df = 5) qqnorm(x); qqline(x)

which will usually (if it is a random sample) show longer tails than expected for a normal. We can make a QQ plot against the generating distribution by
qqplot(qt(ppoints(250), df = 5), x, xlab = "QQ plot for t dsn") qqline(x)

Finally, we might want a more formal test of agreement with normality (or not). R provides the Shapiro-Wilk test
> shapiro.test(long) Shapiro-Wilk normality test data: long W = 0.9793, p-value = 0.01052

and the Kolmogorov-Smirnov test
> ks.test(long, "pnorm", mean = mean(long), sd = sqrt(var(long))) One-sample Kolmogorov-Smirnov test data: long D = 0.0661, p-value = 0.4284 alternative hypothesis: two.sided

(Note that the distribution theory is not valid here as we have estimated the parameters of the normal distribution from the same sample.) Previous: Examining the distribution of a set of data , Up: Probability distributions 8.3 One- and two-sample tests So far we have compared a single sample to a normal distribution. A much more common operation is to compare aspects of two samples. Note that in R, all “classical” tests including the ones used below are in package stats which is normally loaded. Consider the following sets of data on the latent heat of the fusion of ice ( cal/gm ) from Rice (1995, p.490)
Method A: 79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97 80.05 80.03 80.02 80.00 80.02 Method B: 80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97

40 de 99

25/02/2011 10:36

Uma Introdução ao R

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-...

Boxplots provide a simple graphical comparison of the two samples.
A <- scan() 79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97 80.05 80.03 80.02 80.00 80.02 B <- scan() 80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97 boxplot(A, B)

which indicates that the first group tends to give higher results than the second. To test for the equality of the means of the two examples, we can use an unpaired t-test by
> t.test(A, B) Welch Two Sample t-test data: A and B t = 3.2499, df = 12.027, p-value = 0.00694 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 0.01385526 0.07018320 sample estimates: mean of x mean of y 80.02077 79.97875

which does indicate a significant difference, assuming normality. By default the R function does not assume equality of variances in the two samples (in contrast to the similar S-PLUS t.test function). We can use the F test to test for equality in the variances, provided that the two samples are from normal populations.
> var.test(A, B) F test to compare two variances data: A and B F = 0.5837, num df = 12, denom df = 7, p-value = 0.3938 alternative hypothesis: true ratio of variances is not equal to 1 95 percent confidence interval: 0.1251097 2.1052687 sample estimates: ratio of variances 0.5837405

which shows no evidence of a significant difference, and so we can use the classical t-test that assumes equality of the variances.
> t.test(A, B, var.equal=TRUE) Two Sample t-test data: A and B t = 3.4722, df = 19, p-value = 0.002551 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 0.01669058 0.06734788 sample estimates: mean of x mean of y 80.02077 79.97875

All these tests assume normality of the two samples. The two-sample Wilcoxon (or Mann-Whitney) test only assumes a common continuous distribution under the null hypothesis.
> wilcox.test(A, B)

41 de 99

25/02/2011 10:36

p-value = 0. and it may be used wherever any expression may be used.points=FALSE. Commands may be grouped together in braces. Even an assignment is an expression whose result is the value assigned. in particular multiple assignments are possible. B) Note the warning: there are several ties in each sample.Uma Introdução ao R http://translate. B) Two-sample Kolmogorov-Smirnov test data: A and B D = 0. Previous: Probability distributions . There are several ways to compare graphically the two samples. in which case the value of the group is the result of the last expression in the group evaluated.. loops and conditional execution Grouped expressions Control statements Next: Control statements . do. Since such a group is also an expression it may.points=FALSE.. xlim=range(A. p-value = 0. assuming a common continuous distribution: > ks.test(A. verticals=TRUE. Wilcoxon rank sum test with continuity correction data: A and B W = 89. for example. and so on. which suggests strongly that these data are from a discrete distribution (probably due to rounding). be itself included in parentheses and used a part of an even larger expression. Previous: Grouped expressions . Up: Loops and conditional execution 9. The Kolmogorov-Smirnov test is of the maximal vertical distance between the two ecdf's. verticals=TRUE. do.007497 alternative hypothesis: true location shift is not equal to 0 Warning message: Cannot compute exact p-value with ties in: wilcox. expr_m } .2 Control statements 42 de 99 25/02/2011 10:36 . . .5962. add=TRUE) will show the two empirical CDFs. B)) > plot(ecdf(B). Os seguintes > plot(ecdf(A).1 Grouped expressions R is an expression language in the sense that its only command type is a function or expression which returns a result. { expr_1 . Previous: Loops and conditional execution ...googleusercontent. We have already seen a pair of boxplots. and qqplot will perform a QQ plot of the two samples.05919 alternative hypothesis: two-sided Warning message: cannot compute correct p-values with ties in: ks. B) Next: Writing your own functions . Up: Loops and conditional execution 9.com/translate_c?hl=pt-BR&ie=UTF-.test(A. Up: Top 9 Grouping.test(A.

) Warning : for() loops are used in R code much less often than in compiled languages. One possibility here is to use coplot() . otherwise b[i] . yc[[i]])) } (Note the function split() which produces a list of vectors obtained by splitting a larger vector according to the classes specified by a factor. The “short-circuit” operators && and || are often used as part of the condition in an if statement. 19 which will produce an array of plots corresponding to each level of the factor. See the help facility for further details. expr_1 is a vector expression. && and || apply to vectors of length one.2 Repetitive execution: for loops. Previous: Conditional execution .1 Conditional execution: if statements The language has available a conditional construction of the form > if ( expr_1 ) expr_2 else expr_3 where expr_1 must evaluate to a single logical value and the result of the entire expression is then evident. Conditional execution Repetitive execution Next: Repetitive execution . ind) > for (i in 1:length(yc)) { plot(xc[[i]]. Other looping facilities include the > repeat expr 43 de 99 25/02/2011 10:36 . and expr_2 is often a grouped expression with its sub-expressions written in terms of the dummy name . There is a vectorized version of the if / else construct.split(x. yc[[i]]) abline(lsfit(xc[[i]]. As an example. now putting all plots on the one display. b) and returns a vector of the length of its longest argument.. mostly used in connection with boxplots.. with elements a[i] if condition[i] is true. suppose ind is a vector of class indicators and we wish to produce separate plots of y versus x within classes. a. Up: Control statements 9. expr_2 is repeatedly evaluated as name ranges through the values in the vector result of expr_1 . Whereas & and | apply element-wise to vectors.2.googleusercontent. and only evaluate their second argument if necessary. This has the form ifelse(condition. ind) > yc <.Uma Introdução ao R http://translate.com/translate_c?hl=pt-BR&ie=UTF-. the ifelse function. Previous: Control statements .split(y. Another way to do this. Up: Control statements 9.2. This is a useful function. repeat and while There is also a for loop construction which has the form > for ( name in expr_1 ) expr_2 where name is the loop variable. Code that takes a `whole object' view is likely to be both clearer and faster in R. is as follows: > xc <. (often a sequence like 1:20 ).

com/translate_c?hl=pt-BR&ie=UTF-. are themselves written in R and thus do not differ materially from user written functions. Next: Statistical models in R .1 Simple examples As a first example. . The function is defined as follows: 44 de 99 25/02/2011 10:36 ... simpler ways of achieving the same end. to calculate a value. (usually a grouped expression). consider a function to calculate the two sample t-statistic. It should be emphasized that most of the functions supplied as part of the R system. that uses the arguments. the R language allows the user to create objects of mode function ..) and may occur anywhere a function call is legitimate.function( arg_1 .Uma Introdução ao R http://translate. A function is defined by an assignment of the form > name <.) expression The expression is an R expression. Up: Top 10 Writing your own functions As we have seen informally along the way. Simple examples Defining new binary operators Named arguments and defaults The three dots argument Assignment within functions More advanced examples Âmbito Customizing the environment Object orientation Next: Defining new binary operators .. Control statements are most often used in connection with functions which are discussed in Writing your own functions . . The value of the expression is the value returned for the function. These are true R functions that are stored in a special internal form and may be used in further expressions and so on. In the process. of course. convenience and elegance. statement and the > while ( condition ) expr declaração. postscript() and so on. and learning to write useful functions is one of the main ways to make your use of R comfortable and productive. Previous: Writing your own functions . expr_2 . arg_i . This is the only way to terminate repeat loops. showing “all the steps”. The break statement can be used to terminate any loop. the language gains enormously in power.googleusercontent.. Previous: Loops and conditional execution . and where more examples will emerge. such as mean() . This is an artificial example. possibly abnormally. arg_2 .. since there are other. Up: Writing your own functions 10. The next statement can be used to discontinue one particular cycle and skip to the “next”. var() . A call to the function then usually takes the form name ( expr_1 .

> twosam <.var(y1). Up: Writing your own functions 10.coef(X. y) { X <.(yb1 . If so. } (Note the use of quote marks. Next: Named arguments and defaults . which returns the coefficients of the orthogonal projection of the vector y onto the column space of the matrix. y) } After this object is created it may be used in statements such as > regcoeff <.2 Defining new binary operators Had we given the bslash() function a different name. It in turn uses the functions qr() and qr.qr(X) qr... you could perform two sample t-tests using a call such as > tstat <.var(y2) s <.) The matrix multiplication operator. where (X'X)^{-} is a generalized inverse of X'X.mean(y2) s1 <. (The backslash symbol itself is not a convenient choice as it presents special problems in this context.((n1-1)*s1 + (n2-1)*s2)/(n1+n2-2) tst <. y) { . X. (This is ordinarily called the least squares estimate of the regression coefficients. tstat As a second example. Previous: Simple examples .length(y2) yb1 <.function(y1. we may wish to make it a matrix binary operator for even more convenient use..) This would ordinarily be done with the qr() function..length(y1). > bslash <. The function definition would then start as > "%!%" <. 45 de 99 25/02/2011 10:36 .yb2)/sqrt(s*(1/n1 + 1/n2)) TST } With this function defined. The classical R function lsfit() does this job quite well. we choose ! for the internal character. Hence there is probably some value in having just this part isolated in a simple to use function if it is going to be in frequent use. however this is sometimes a bit tricky to use directly and it pays to have a simple function such as the following to use it safely. namely one of the form % anything % it could have been used as a binary operator in expressions rather than in function form.twosam(data$male. consider a function to emulate directly the MATLAB backslash command. data$female). y2) { n1 <. %*% . Suppose.coef() in the slightly counterintuitive way above to do this part of the calculation. yb2 <. and more 20 . s2 <.googleusercontent.function(X.mean(y1). Thus given an by 1 vector y and an n by p matrix X then X \ y is defined as (X'X)^{-}X'y.Uma Introdução ao R http://translate. for example.bslash(Xmat. yvar) e assim por diante. n2 <.com/translate_c?hl=pt-BR&ie=UTF-.) The function could then be used as X %!% y .function(X. and the outer product matrix operator %o% are other examples of binary operators defined in this way.

data. limit=20) > ans <. for more details on the par() function.fun1(d.. and specify named arguments after the positional arguments.frame. df. literally ' .4 The ' . in which case they may be omitted altogether from the call when the defaults are appropriate.function(data. ... limit=10) which changes one of the defaults. graph=TRUE.. if fun1 were defined as > fun1 <.frame.) This can be done by including an extra argument.3 Named arguments and defaults As first noted in Generating regular sequences . limit=20. fun1 <. 20) > ans <. which may then be passed on.fun1(d.. graph=TRUE.function(data. limit) { [function body omitted] } then the function may be invoked in several ways. } it could be called as > ans <... limit=20) { . graph=TRUE.googleusercontent.Uma Introdução ao R http://translate. Up: Writing your own functions 10. data. data. even involving other arguments to the same function. Thus if there is a function fun1 defined by > fun1 <.. . Furthermore the argument sequence may begin in the unnamed. Previous: Named arguments and defaults . df. data.) 46 de 99 25/02/2011 10:36 . TRUE.) { [omitted statements] if (graph) par(pch="*". df. Up: Writing your own functions 10. positional form. Next: The three dots argument .frame=df) are all equivalent. graph=TRUE..function(data. they are not restricted to be constants as in our simple example here. graph. It is important to note that defaults may be arbitrary expressions.fun1(d. An outline example is given below. For example many graphics functions use the function par() and functions like plot() allow the user to pass on graphical parameters to par() to control the graphical output. of the function. For example.fun1(d. if arguments to called functions are given in the “ name = object ” form. they may be given in any order. limit=20. or as > ans <. ' argumento Another frequent requirement is to allow one function to pass on argument settings to another.fun1(data=d. df) which is now equivalent to the three cases above. In many cases arguments can be given commonly appropriate default values. '. (See The par() function . Next: Assignment within functions .... Previous: Defining new binary operators .frame. for example > ans <.com/translate_c?hl=pt-BR&ie=UTF-.

. S-PLUS users should be aware that <<.as. say blocks ( b levels) and varieties ( v levels).svd(A) list(eff=1 . (Some aspects of this problem have already been discussed in Index matrices . See the help document for details. though hardly difficult.factor(blocks) # minor safety move b <.6 More advanced examples Efficiency factors in block designs Dropping all names in a printed array Recursive numerical integration Next: Dropping all names in a printed array .1/sqrt(K) * N * rep(1/sqrt(R). consider finding the efficiency factors for a block design. blockcv=sv$u. and N is the b by v incidence matrix.Uma Introdução ao R http://translate. varieties) A <. example of a function. varietycv=sv$v) } 47 de 99 25/02/2011 10:36 . Next: Scope .sv$d^2. topic and is not covered further here. This is a somewhat advanced.length(levels(blocks)) varieties <. <<.vector(table(blocks)) # remove dim attr R <.table(blocks. If global and permanent assignments are intended within a function.qr(X) does not affect the value of the argument in the calling program.factor(varieties) # minor safety move v <. [more omissions] } Next: More advanced examples . > bdeff <.A'A.5 Assignments within functions Note that any ordinary assignments done within the function are local and temporary and are lost after exit from the function . varieties) { blocks <. respectively. then either the “superassignment” operator.R^{-1/2}N'K^{-1}NR^{-1/2} = I_v . rep(b. v)) sv <. where A = K^{-1/2}NR^{-1/2}. Previous: The three dots argument . To understand completely the rules governing the scope of R assignments the reader needs to be familiar with the notion of an evaluation frame . Previous: Assignment within functions . then the efficiency factors are defined as the eigenvalues of the matrix E = I_v .has different semantics in R. Up: Writing your own functions 10. These are discussed further in Scope .as. If R and K are the v by v and b by b replications and block size matrices. Up: More advanced examples 10.as. Previous: More advanced examples .or the function assign() can be used.vector(table(varieties)) # remove dim attr N <.) A block design is defined by two factors.as. One way to write the function is given below.com/translate_c?hl=pt-BR&ie=UTF-.function(blocks. if a little pedestrian. Thus the assignment X <.1 Efficiency factors in block designs As a more complete. Up: Writing your own functions 10.googleusercontent.length(levels(varieties)) K <..6.

l + 1]] <.dimnames() .3 Recursive numerical integration Functions may be recursive. rep("". The integrand is evaluated at the end points of the range and in the middle.dimnames <. rm(temp) This can be much more conveniently done using a function. since sometimes these give additional useful qualitative information. Previous: Dropping all names in a printed array . it is often useful to print them in close block form without the array names or numbers.d um } array for compact printing. no. With this function defined. no.function(a) { ## Remove all dimension names from an d <. Note. then the latter is returned as the value.0 for(i in dim(a)) { d[[l <. shown below. Otherwise the same process is recursively applied to each panel. There is.. The example below shows a naive way of performing one-dimensional numerical integration. Next: Recursive numerical integration .rep("".X > dimnames(temp) <. Up: More advanced examples 10. X > temp <. 48 de 99 25/02/2011 10:36 .list() l <. i) } dimnames(a) <.6. a heavy overhead. however. nrow(X)). that such functions. It also illustrates how some effective and useful user functions can be quite short. an array may be printed in close format using > no. or indeed variables.list(rep("".com/translate_c?hl=pt-BR&ie=UTF-. If the one-panel trapezium rule answer is close enough to the two panel. as a “wrap around” to achieve the same result. where patterns are the real interest rather than the values. however.Uma Introdução ao R http://translate. Removing the dimnames attribute will not achieve this effect. It is numerically slightly better to work with the singular value decomposition on this occasion rather than the eigenvalue routines.6.googleusercontent. For example to print a matrix.. Up: More advanced examples 10. are not inherited by called functions in higher evaluation frames as they would be if they were on the search path. ncol(X))) > temp. but rather the array must be given a dimnames attribute consisting of empty strings. but also the block and variety canonical contrasts. The result is an adaptive integration process that concentrates function evaluations in regions where the integrand is farthest from linear. and the function is only competitive with other algorithms when the integrand is both smooth and very difficult to evaluate. Previous: Efficiency factors in block designs . The result of the function is a list giving not only the efficiency factors as the first component.2 Dropping all names in a printed array For printing purposes with large matrices or arrays. and may themselves define functions within themselves.dimnames(X) This is particularly useful for large integer arrays.

However. Variables which are not formal parameters or local variables are called free variables. a. fun) { ## function `fun1' is only visible inside `area' d <. lim . area <. fd. Under 49 de 99 25/02/2011 10:36 . a0. a0. eps.a2) < eps || lim == 0) return(a1 + a2) else { return(fun(f. fb. The formal parameters of a function are those occurring in the argument list of the function. it details one of the major differences between S-PLUS and R. lim. Under static scope ( S-PLUS ) the value is that associated with a global variable named n .a)/4 fd <. a2. fa. Free variables become local variables if they are assigned to. x is a formal parameter. lim = 10) { fun1 <. b. lim .0e-06. fun)) } } fa <. eps.f(d) a1 <.function(x) { y <. d. First we define a function called cube .(a + b)/2 h <.7 Scope The discussion in this section is somewhat more technical than in other parts of this document.function(f.h * (fd + fb) if(abs(a0 . The symbols which occur in the body of a function can be divided into three classes.f(b) a0 <. fb.a))/2 fun1(f. b. cube <.function(n) { sq <. Their values are determined by the process of binding the actual function arguments to the formal parameters. Consider the following function definition.. eps. fa. d. eps = 1.((fa + fb) * (b .. eps.function() n*n n*sq() } The variable n in the function sq is not an argument to that function. Previous: More advanced examples . Up: Writing your own functions 10. b. a. fun) + fun(f.googleusercontent.f(a) fb <. local variables and free variables. This is called lexical scope .1. Therefore it is a free variable and the scoping rules must be used to ascertain the value that is to be associated with it. f <.(b .com/translate_c?hl=pt-BR&ie=UTF-.1. lim. fb. a. fun1) } Âmbito Object orientation Next: Customizing the environment . y is a local variable and z is a free variable. a.2*x print(x) print(y) print(z) } In this function.h * (fa + fd) a2 <. fa.Uma Introdução ao R http://translate. formal parameters. a1. Local variables are those whose values are determined by the evaluation of expressions in the body of the functions.a1 . In R the free variable bindings are resolved by first looking in the environment in which the function was created.function(f. b. The example is also given partly as a little puzzle in R programming. fd.

A functioning bank account needs to have a balance or total. total. The special assignment operator. lexical scope (R) it is the parameter to the function cube since that is the active binding for the variable n at the time the function sq was defined.account(100) robert <.account(200) ross$withdraw(30) ross$balance() robert$balance() ross$deposit(50) ross$balance() ross$withdraw(500) 50 de 99 25/02/2011 10:36 .creates a global variable and assigns the value of the right hand side to it 21 . is used to change the value associated with total . The difference between evaluation in R and evaluation in S-PLUS is that S-PLUS looks for a global variable called n while R first looks for a variable called n in the environment created when cube was invoked. a function for making deposits and a function for stating the current balance.open. If the global or top-level environment is reached without finding the symbol total then that variable is created and assigned to there.googleusercontent. ## first evaluation in S S> cube(2) Error in sq(): Object "n" not found Largaram S> n <. "\n\n") } balance = function() { cat("Your balance is".. "withdrawn. This operator looks back in enclosing environments for an environment that contains the symbol total and when it finds such an environment it replaces the value. Your balance is".total + amount cat(amount.com/translate_c?hl=pt-BR&ie=UTF-.has been used in a function that was returned as the value of another function will the special behavior described here occur. with the value of right hand side. In the following example we show how R can be used to mimic a bank account. Your balance is". a function for making withdrawals.account <. We achieve this by creating the three functions within account and then returning a list containing them. Because these functions are defined in an environment which contains total .amount cat(amount. Only when <<. total..total .3 S> cube(2) [1] 18 ## then the same function evaluated in R R> cube(2) [1] 8 Lexical scope can also be used to give functions mutable state . open. When account is invoked it takes a numerical argument total and returns a list containing the three functions.Uma Introdução ao R http://translate. <<. in that environment.open. "\n\n") } withdraw = function(amount) { if(amount > total) stop("You don't have that much money!\n") total <<. For most users <<. total..function(total) { list( deposit = function(amount) { if(amount <= 0) stop("Deposits must be positive!\n") total <<. "deposited. they will have access to its value. "\n\n") } ) } ross <.

. profile file named .9 Classes.getenv("HOME"). If that variable is unset. "mystuff. There is a site initialization file and every directory can have its own special initialization file. The location of the site initialization file is taken from the value of the R_PROFILE environment variable. "R". generic functions and object orientation The class of an object determines how it will be treated by what are known as generic functions. > . the file it points to is used instead of the .8 Customizing the environment Users can customize their environment in several different ways. Any function named . An example makes things clearer.Rprofile 22 can be placed in any directory. Put the other way round.site in the R home subdirectory etc is used.. length=999) # custom numbers and printout x11() # for graphics par(pch = "+") # plotting character source(file. Thus.First() in either of the two profile files or in the .Uma Introdução ao R http://translate.RData image has a special status.Last can be used.Rprofile file in the user's home directory and uses that (if it exists). personal. If no .Last() .Rprofile file is found in the startup directory. Up: Writing your own functions 10.googleusercontent. Rprofile. a generic function performs a task or action on its arguments specific to the class of the argument itself .function() { options(prompt="$ ". For example. the file Rprofile.First() ..path(Sys. This file gives individual users control over their workspace and allows for different startup procedures in different working directories. Previous: Scope .First and . This file should contain the commands that you want to execute every time R is started under your system. Among the other generic functions are plot() 51 de 99 25/02/2011 10:36 . if defined. Up: Writing your own functions 10.site . continue="+\t") # $ is the prompt options(digits=5. the definition in the example below alters the prompt to $ and sets up various other useful things that can then be taken for granted in the rest of the session. A second. the special functions . Finally.Rprofile files. > . An example is given below. The class mechanism offers the user the facility of designing and writing generic functions for special purposes. cat(paste(date(). A definition in later files will mask definitions in earlier files. If R is invoked in that directory then that file will be sourced. the sequence in which files are executed is. If the argument lacks any class attribute.Last <.R")) # my personal functions library(MASS) # attach a package } Similarly a function . then R looks for a . Next: Object orientation . there is always a default action provided.function() { graphics.com/translate_c?hl=pt-BR&ie=UTF-."\nAdios\n")) # Is it } time for lunch? Previous: Customizing the environment . It is automatically performed at the beginning of an R session and may be used to initialize the environment. or has a class not catered for specifically by the generic function in question. the user profile. If the environment variable R_PROFILE_USER is set.First <. is (normally) executed at the very end of the session.off() # a small safety measure.RData and then .

com/translate_c?hl=pt-BR&ie=UTF-.aov") A single object matching 'coef. and anova() for comparing statistical models.any as. For example the plot() function has a default method and variants for objects of classes "data.nls* coef. and more..default* coef.summary.aov' was found It was found in the following places registered S3 method for coef from namespace stats namespace:stats com valor function (object. the functions that can accommodate in some fashion objects of class "data. A complete list can be got again by using the methods() function: > methods(plot) For many generic functions the function body is quite short.object$coef z[!is..frame" . "factor" .na(z)] } > getS3method("coef". "density" .. Next: Graphics .Uma Introdução ao R http://translate.) { z <.aov* coef.mean plot summary A currently complete list can be got by using the methods() function: > methods(class="data. The number of generic functions that can treat a class in a specific way can be quite large.matrix [<. We can read these by either of > getAnywhere("coef. summary() for summarizing analyses of various types.. Up: Top 52 de 99 25/02/2011 10:36 .. .nls* Non-visible functions are asterisked In this example there are six methods.object$coef z[!is. for example > coef function (object.frame") Conversely the number of classes a generic function can handle can also be quite large.listof* [5] coef. To see what methods are available we can use methods() > methods(coef) [1] coef.) { z <.. Previous: Writing your own functions . none of which can be seen by typing its name.na(z)] } The reader is referred to the R Language Definition for a more complete discussion of this mechanism..) UseMethod("coef") The presence of UseMethod indicates this is a generic function.googleusercontent. For example.frame" include [ [[<.Arima* coef. for displaying objects graphically. . "aov") function (object. ..

. 11 Statistical models in R This section presumes the reader has some familiarity with statistical methodology. . . 53 de 99 25/02/2011 10:36 .. . are factors. y ~ 0 + x y ~ -1 + x y ~ x .. X is a matrix and A . a few examples may usefully set the picture. x .. The first has an implicit intercept term. Suppose y . where the e_i are NID(0.. y ~ x y ~ 1 + x Both imply the same simple linear regression model of y on x. in particular with regression analysis and the analysis of variance. Previous: Statistical models in R . formulae The template for a statistical model is a linear regression model with independent. are numeric variables. The requirements for fitting statistical models are sufficiently well defined to make it possible to construct general tools that apply in a broad spectrum of problems. Exemplos Before giving a formal specification. X is the model matrix or design matrix and has columns x_0. n. x_1. Later we make some rather more ambitious presumptions. In matrix terms this would be written y = X beta + e where the y is the response vector. without an intercept term). ... x_p. i = 1. Formulae for statistical models Linear models Generic functions for extracting model information Analysis of variance and model comparison Updating fitted models Generalized linear models Nonlinear least squares and maximum likelihood models Some non-standard models Next: Linear models . C . R provides an interlocking suite of facilities that make fitting statistical models very simple.. x2 . x0 . and one needs to ask for the details by calling extractor functions.googleusercontent..1 Simple linear regression of y on x through the origin (that is.com/translate_c?hl=pt-BR&ie=UTF-. the determining variables. Very often x_0 will be a column of ones defining an intercept term. the basic output is minimal.1 Defining statistical models. B .. . Up: Statistical models in R 11.Uma Introdução ao R http://translate. x1 . and the second an explicit one. The following formulae on the left side below specify statistical models as described on the right. As we mention in the introduction. homoscedastic errors y_i = sum_{j=0}^p beta_j x_{ij} + e_i. namely that something is known about generalized linear models and nonlinear regression. . sigma^2).

googleusercontent. log(y) ~ x1 + x2 Multiple regression of the transformed variable.. term_i is either a vector or matrix expression.com/translate_c?hl=pt-BR&ie=UTF-. a factor. and the second uses explicit powers. and error strata determined by factor C. The form. with whole plots (and hence also subplots). (the first is optional). or 1 . A and B.. y ~ A Single classification analysis of variance model of y. y ~ A + x Single classification analysis of covariance model of y. with different codings. y ~ A*B + Error(C) An experiment with two treatment factors. either + or . or a formula expression consisting of factors. is response ~ op_1 term_1 op_2 term_2 op_3 term_3 .. y y y y ~ ~ ~ ~ A*B A + B + A:B B %in% A A/B Two factor non-additive model of y on A and B. vectors or matrices connected by formula operators .2) Multiple regression y with model matrix consisting of the matrix X as well as polynomial terms in x to degree 2. determined by factor C. implying the inclusion or exclusion of a term in the model. y ~ poly(x. 54 de 99 25/02/2011 10:36 . with classes determined by A. The first form uses orthogonal polynomials. as basis. op_i is an operator. y ~ (A + B + C)^2 y ~ A*B*C . For example a split plot experiment. y ~ A * x y ~ A/x y ~ A/(1 + x) . The operator ~ is used to define a model formula in R. y ~ X + poly(x. (or expression evaluating to a vector or matrix) defining the response variable(s)..A:B:C Three factor experiment but with a model containing main effects and two factor interactions only. The last form produces explicit estimates of as many different intercepts and slopes as there are levels in A. In abstract terms all four specify the same model subspace. onde resposta is a vector or matrix. The first two specify the same crossed classification and the second two specify the same nested classification. and with covariate x. log(y).Uma Introdução ao R http://translate. with classes determined by A. on x1 and x2 (with an implicit intercept term). Both formulae specify the same model.1 Separate simple linear regression models of y on x within the levels of A. for an ordinary linear model..2) y ~ 1 + x + I(x^2) Polynomial regression of y on x of degree 2.

This is easy if we have continuous variables.) For ordered factors the k . then the “subclasses” factor. . M_1 * M_2 M_1 + M_2 + M_1 : M_2 . Note that inside the parentheses that usually enclose function arguments all operators have their normal arithmetic meaning.googleusercontent. One inevitable change is that the operator ' ..Uma Introdução ao R http://translate. M_1 %in% M_2 Similar to M_1 : M_2 .. The function I() is an identity function used to allow terms in model formulae to be defined using arithmetic operators. Note particularly that the model formulae specify the columns of the model matrix . p.1 columns are the orthogonal polynomials on 1. In all cases each term defines a collection of columns either to be added to or removed from the model matrix.1. M_1 : M_2 The tensor product of M_1 and M_2 . if the intercept is 55 de 99 25/02/2011 10:36 . the specification of the parameters being implicit. This is not the case in other contexts. For unordered factors k . (Thus the implicit parameterization is to contrast the response at each level with that at the first. First.1 columns are generated for the indicators of the second. The notation is summarized below (based on Chambers & Hastie.. M^n All terms in M together with “interactions” up to order n I( M ) Insulate M . it is not the whole story.. for example in specifying nonlinear models. M_1 . What about a k-level factor A ? The answer differs for unordered and ordered factors. k. Inside M all operators have their normal arithmetic meaning. Contrasts Previous: Formulae for statistical models .1 Contrasts We need at least some idea how the model formulae specify the columns of the model matrix. omitting the constant term. The formula operators are similar in effect to the Wilkinson and Rogers notation used by such programs as Glim and Genstat. kth levels of the factor.. M_1 + M_2 Include M_1 and M_2 .M_2 Include M_1 leaving out terms of M_2 . .com/translate_c?hl=pt-BR&ie=UTF-. If both terms are factors. . and that term appears in the model matrix. Up: Formulae for statistical models 11. A 1 stands for an intercept column and is by default included in the model matrix unless explicitly removed. as each provides one column of the model matrix (and the intercept will provide a column of ones if included in the model).. but with a different coding. Although the answer is already complicated. M_1 / M_2 M_1 + M_2 %in% M_1 .29): Y~M Y is modeled as M . ' becomes ' : ' since the period is a valid name character in R. . 1992.

Previous: Formulae for statistical models . you will need to set options(contrasts = c("contr. S using Helmert contrasts. Although the details are complicated.2 Linear models The basic function for fitting ordinary multiple models is lm() . "contr. the first such term is encoded into k columns giving the indicators for all the levels.com/translate_c?hl=pt-BR&ie=UTF-. the whole behavior can be changed by the options setting for contrasts . Up: Statistical models in R 11.Uma Introdução ao R http://translate.. as treatment contrasts (R's default) are thought easier for newcomers to interpret.poly")) This is a deliberate difference.model <. Next: Generic functions for extracting model information .lm(y ~ x1 + x2.treatment". data = data. "contr. model formulae in R will normally generate the models that an expert statistician would expect.helmert". We have not yet considered interaction terms: these generate the products of the columns introduced for their component terms. for example.3 Generic functions for extracting model information The value of lm() is a fitted model object. technically a list of results of class "lm" . omitted in a model that contains a factor term. Previous: Linear models . plotted and so on by using generic functions that orient themselves to objects of class "lm" .. Next: Analysis of variance and model comparison . and a streamlined version of the call is as follows: > fitted. This is the case regardless of whether data frame production has been attached on the search path or not .poly")) The main reason for mentioning this is that R and S have different defaults for unordered factors. and is for experts only. extracted. Up: Statistical models in R 11. So if you need to compare your results to those of a textbook or paper which used S-PLUS . The default setting in R is options(contrasts = c("contr.googleusercontent. data = production) would fit a multiple regression model of y on x1 and x2 (with implicit intercept term). Fitting. We have still not finished. provided that marginality is preserved.lm( formula . as the contrast scheme to be used can be set for each term in the model using the functions contrasts and C . Estes incluem add1 deviance formula predict step alias drop1 kappa print summary anova effects labels proj vcov coef family plot residuals 56 de 99 25/02/2011 10:36 . Information about the fitted model can then be displayed. a model with an interaction but not the corresponding main effects will in general lead to surprising results. Second. The important (but technically optional) parameter data = production specifies that any variables needed to construct the model should come first from the production data frame .frame ) Por exemplo > fm2 <.

Short form: resid( object ) .Uma Introdução ao R http://translate.com/translate_c?hl=pt-BR&ie=UTF-. formula( object ) Extract the model formula. step( object ) Select a suitable model by adding or dropping terms and preserving hierarchies. weighted if appropriate.. fitted values and some diagnostics.. coef( object ) Extract the regression coefficient (matrix). summary( object ) Print a comprehensive summary of the results of the regression analysis. The value is a vector or matrix of predicted values corresponding to the determining variable values in data. weighted as appropriate. residuals( object ) Extract the (matrix of) residuals.frame ) The data frame supplied must have variables specified with the same labels as the original. A brief description of the most commonly used ones is given below. plot( object ) Produce four plots. predict( object . object_2 ) Compare a submodel with an outer model and produce an analysis of variance table. newdata= data. anova( object_1 . 57 de 99 25/02/2011 10:36 .frame . Most often used implicitly. deviance( object ) Residual sum of squares. The model with the smallest value of AIC (Akaike's An Information Criterion) discovered in the stepwise search is returned. print( object ) Print a concise version of the object. Long form: coefficients( object ) . showing residuals.googleusercontent.

4 Analysis of variance and model comparison The model fitting function aov(formula. 58 de 99 25/02/2011 10:36 .googleusercontent. For multistratum experiments the procedure is first to project the response onto the error strata.) The display is then an ANOVA table showing the differences between the fitted models when fitted in sequence. data=farm. between blocks” and “within blocks”. but rather makes it easier to comprehend and control. strata. It should be noted that in addition aov() allows an analysis of models with multiple error strata such as split plot experiments. A more flexible alternative to the default full ANOVA table is to compare two or more models directly using the anova() function. when it defines a two strata experiment.formula is simply a factor.2 . . The model formula response ~ mean. “within farms. see Chambers & Hastie (1992). and most of the generic functions listed in the table in Generic functions for extracting model information apply. Previous: Generic functions for extracting model information . or balanced incomplete block designs with recovery of inter-block information. again in sequence. For further details.formula ) specifies a multi-stratum experiment with error strata defined by the strata.Uma Introdução ao R http://translate.model. namely between and within the levels of the factor. namely “between farms”. Next: Updating fitted models . The fitted models being compared would usually be an hierarchical sequence. This does not give different information to the default.. data= data.com/translate_c?hl=pt-BR&ie=UTF-. with all determining variables factors. fitted.1 ANOVA tables Note also that the analysis of variance table (or tables) are for a sequence of fitted models. For example.model. vcov( object ) Returns the variance-covariance matrix of the main parameters of a fitted model object. ANOVA tables Previous: Analysis of variance and model comparison . In the simplest case..4. a model formula such as that in: > fm <.. The sums of squares shown are the decrease in the residual sums of squares resulting from an inclusion of that term in the model at that place in the sequence. and to fit the mean model to each projection.data) would typically be used to describe an experiment with mean model v + n*p*k and three error strata. Up: Analysis of variance and model comparison 11.formula + Error( strata.formula .1 . Up: Statistical models in R 11. of course. > anova( fitted. Hence only for orthogonal experiments will the order of inclusion be inconsequential.frame ) operates at the simplest level in a very similar way to the function lm() .aov(yield ~ v + n*p*k + Error(farms/blocks)..

The stimulus variables influence the distribution of y through a single linear function..) ~ . can be used to stand for “the corresponding part of the old model formula”.. Up: Statistical models in R 11. Por exemplo. only. y. A generalized linear model may be described in terms of the following sequence of assumptions: There is a response. sqrt(.. Its form is > new. . The names of these give a good clue to their purpose. data = production) would fit a model with response y and regressor variables all other variables in the data frame production . This linear function is called the linear predictor . this information is passed on through the fitted model object to update() and its allies.formula ) In the new.googleusercontent.5 Updating fitted models The update() function is largely a convenience function that allows a model to be fitted that differs from one previously fitted usually by just a few additional or removed terms.) would fit a five variate multiple regression with variables (presumably) from the data frame production . x_2. > fm05 <..lm(y ~ x1 + x2 + x3 + x4 + x5. only . of interest and stimulus variables x_1. data = production) > fm6 <.com/translate_c?hl=pt-BR&ie=UTF-. The distribution of y is of the form f_Y(y. The name ' . Other functions for exploring incremental sequences of models are add1() . Previous: Analysis of variance and model comparison . ' can also be used in other contexts. drop1() and step() . Next: Nonlinear least squares and maximum likelihood models . but for full details see the on-line help.model <. Previous: Updating fitted models . mu. ' .6 Generalized linear models Generalized linear modeling is a development of linear models to accommodate both non-normal response distributions and transformations to linearity in a clean and straightforward way. but with slightly different meaning. Up: Statistical models in R 11.Uma Introdução ao R http://translate.update(fm05.. phi)) 59 de 99 25/02/2011 10:36 . . and fit a variant on the model where the response had a square root transform applied.update(fm6..formula the special name consisting of a period. + beta_p x_p. new.gamma(lambda(mu))) + tau(y. Por exemplo > fmfull <. phi) = exp((A/phi) * (y lambda(mu) . . + x6) > smf6 <. Next: Generalized linear models . ~ .lm(y ~ .model . Note especially that if the data= argument is specified on the original call to the model fitting function. . whose values influence the distribution of the response. and is usually written eta = beta_1 x_1 + beta_2 x_2 + .update( old. hence x_i has no influence on the distribution of y if and only if beta_i is zero. '. fit an additional model including a sixth regressor variable.

a link function and various other pieces of information that are needed to carry out the modeling exercise is called the family of the generalized linear model.. binomial . Those automatically available are shown in the following table: Nome de Família binomial gaussian Gamma inverse. The mean. Up: Generalized linear models 11. eta = m^{-1}(mu) = ell(mu) and this inverse function. The family has to be specified in a different way. ell().com/translate_c?hl=pt-BR&ie=UTF-. cloglog .6. is called the link function . The R function to fit a generalized linear model is glm() which uses the form 60 de 99 25/02/2011 10:36 . probit .gaussian poisson quasi Link functions logit .Uma Introdução ao R http://translate. A represents a prior weight. where phi is a scale parameter (possibly known). 1/mu^2 . Up: Generalized linear models 11. such as McCullagh & Nelder (1989) or Dobson (1990). is a smooth invertible function of the linear predictor: mu = m(eta).1 Families The class of generalized linear models handled by facilities supplied in R includes gaussian . at least approximately. inverse . log . sqrt logit . sqrt The combination of a response distribution. inverse identity . log . inverse .. Famílias The glm() function Next: The glm() function . the same mechanism as was used for linear models can still be used to specify the linear part of a generalized model. but tight enough to allow the development of a unified methodology of estimation and inference. and is constant for all observations. cloglog identity . log . mu. assumed known but possibly varying with the observations. probit . So it is assumed that the distribution of y is determined by its mean and possibly a scale parameter as well.2 The glm() function Since the distribution of the response depends on the stimulus variables through a single linear function only . but in other cases this function is implied by the response distribution. The reader is referred to any of the current reference works on the subject for full details. log . Previous: Families . log 1/mu^2 .6. and $\mu$ is the mean of y. log identity . identity . Previous: Generalized linear models . These assumptions are loose enough to encompass a wide class of models useful in statistical practice.googleusercontent. inverse . inverse gaussian and gamma response distributions and also quasi-likelihood models where the response distribution is not explicitly specified. poisson . In the latter case the variance function must be specified as a function of the mean. Each response distribution admits a variety of link functions to connect the mean with the linear predictor. identity .

y = c(6. The gaussian family A call such as > fm <.glm(y ~ x1 + x2. family= family. and in the logit case (the default). the point at which the argument of the distribution function is zero.55. family = gaussian. data=sales) but much less efficiently. In the case of the quasi family.35. both models have the form y ~ B(n. It is the name of a function that generates a list of functions and expressions that together define and control the model and estimation process. in parentheses as a parameter. data = sales) achieves the same result as > fm <.beta_0/beta_1 that is. F(beta_0 + beta_1 x)) where for the probit case.glm( formula .70). which is the instrument by which the family is described. Where there is a choice of links. Some examples make the process clear..generator . Samples of islander males of various ages were tested for blindness and the results recorded. F(z) = Phi(z) is the standard normal distribution function. If a problem requires a gaussian family with a nonstandard link. The data is shown below: Idade: 20 35 45 55 70 No. blind: 6 17 26 37 44 The problem we consider is to fit both logistic and probit models to this data. > fitted. artificial example. from Silvey (1970).generator . the variance function may also be specified in this way. Note how the gaussian family is not automatically provided with a choice of links. so no parameter is allowed.37. data= data.44)) To fit a binomial model using glm() there are three possibilities for the response: 61 de 99 25/02/2011 10:36 .26. F(z) = e^z/(1+e^z).45. that is the age at which the chance of blindness for a male inhabitant is 50%. The first step is to set the data up as a data frame > kalythos <.frame ) The only new feature is the family. as we shall see later. this can usually be achieved through the quasi family. The names of the standard.frame(x = c(20. n = rep(50.lm(y ~ x1+x2.data. Although this may seem a little complicated at first sight. The binomial family Consider a small. the name of the link may also be supplied with the family name. and to estimate for each model the LD50.5). supplied family generators are given under “Family Name” in the table in Families .googleusercontent. tested: 50 50 50 50 50 No.com/translate_c?hl=pt-BR&ie=UTF-. On the Aegean island of Kalythos the male inhabitants suffer from a congenital eye disease.. If y is the number of blind at age x and n the number tested. its use is quite simple. the effects of which become more marked with increasing age.model <.Uma Introdução ao R http://translate. In both cases the LD50 is LD50 = .17.

It even forms a major part of the use of non-gaussian generalized models overall. Supposing a suitable data frame to be set up we could fit this non-linear regression as 62 de 99 25/02/2011 10:36 . so we add a matrix to our data frame: > kalythos$Ymat <. This is a large and important subject we will not discuss further here. If the response is a two-column matrix it is assumed that the first column holds the number of successes for the trial and the second holds the number of failures. kalythos$n . this family provides a way of fitting gaussian models with non-standard link functions or variance functions. data = worm. family = poisson(link=sqrt).glm(Ymat ~ x. ldl) The actual estimates from this data are 43. Since quasi-likelihood estimation uses formally identical techniques to those for the gaussian distribution.kalythos$y) To fit the models we use > fmp <.theta_2) + e which may be written alternatively as y = 1 / (beta_1 x_1 + beta_2 x_2) + e where x_1 = z_2/z_1. As a graceful alternative to the latter. data = kalythos) Since the logit link is the default the parameter may be omitted on the second call. Poisson models With the Poisson family the default link is the log . If the response is a vector it is assumed to hold binary data. and in practice the major use of this family is to fit surrogate Poisson log-linear models to frequency data. beta_1 = 1/theta_1.googleusercontent. data = kalythos) > fml <..Uma Introdução ao R http://translate. incidentally.663 years and 43.ld50(coef(fmp)). Here we need the second of these conventions. If the response is a factor .. but rather only a link function and the form of the variance function as it depends on the mean.ld50(coef(fml)). To find the LD50 estimate we can use a simple function: > ld50 <. For example. consider fitting the non-linear regression y = theta_1 z_1 / (z_2 . for example for the poisson distribution Var(y) = mu. and beta_2 = theta_2/theta_1.com/translate_c?hl=pt-BR&ie=UTF-.function(b) -b[1]/b[2] > ldp <. ldl <. x_2 = -1/z_1. family = binomial(link=probit).glm(y ~ A + B + x. a Poisson generalized linear model may be fitted as in the following example: > fmod <.cbind(kalythos$y. c(ldp. whose actual distribution is often multinomial.601 years respectively. The form of dependence of the variance on the mean is a characteristic of the response distribution. Occasionally genuinely Poisson data arises in practice and in the past it was often analyzed as gaussian data after either a log or a square-root transformation. family = binomial. For quasi-likelihood estimation and inference the precise response distribution is not specified. To see the results of each fit we could use > summary(fmp) > summary(fml) Both models fit (all too) well. and so must be a 0/1 vector.counts) Quasi-likelihood models For all families the variance of the response will depend on the mean and will have the scale parameter as a multiplier. its first level is taken as failure (0) and all other levels as `success' (1).glm(Ymat ~ x.

and superimpose the model curve using those values. 139.11.56. and out$estimate are the least squares estimates of the parameters. 47. Up: Statistical models in R 11.02.10) > y <. family = quasi(link=inverse. 1. 1.c(0. 0. > plot(x. yfit)) We could do better. Unlike linear regression for example. This method makes sense if the observed errors could have plausibly arisen from a normal distribution.glm(y ~ x1 + x2 .06.7. 123. 191.1 seem adequate. 0. 0.seq(.googleusercontent. which provide the functionality (and more) of S-P LUS 's ms() and nlminb() . But in the majority of cases we have to approach the nonlinear curve fitting problem as one of nonlinear optimization.56. 1. Next: Some non-standard models . as needed. 0.function(p) sum((y . > nlfit <. 0. and convergence may depend critically upon the quality of the starting values.1. 0. Up: Nonlinear least squares and maximum likelihood models 11. 159.Uma Introdução ao R http://translate. 0. hessian = TRUE) After the fitting.0) nlminb() . We seek the parameter values that minimize some index of lack-of-fit.10. 0. 152.22.(p[1] * x)/(p[2] + x))^2) In order to do the fit we need initial estimates of the parameters. 97. R's nonlinear optimization routines are optim() .c(76. Here is an example from Bates & Watts (1988). One way to find sensible starting values is to plot the data. there is no guarantee that the procedure will converge on satisfactory estimates.11. p = c(200.02. Now do the fit: > out <. .02.1). All the methods require initial guesses about what parameter values to try. 107.2. 207. 200) The fit criterion to be minimized is: > fn <..06. and they do this by trying out various parameter values iteratively.1 Least squares One way to fit a nonlinear model is by minimizing the sum of the squared errors (SSE) or residuals. 0. guess some parameter values. nlm() and (from R 2. To obtain the approximate standard errors (SE) of the estimates we do: 63 de 99 25/02/2011 10:36 . but these starting values of 200 and 0. Previous: Nonlinear least squares and maximum likelihood models .200 * xfit/(0.7 Nonlinear least squares and maximum likelihood models Certain forms of nonlinear model can be fitted by Generalized Linear Models ( glm() ).nlm(fn. variance=constant). The data are: > x <. data = biochem) The reader is referred to the manual and the help document for further information.1 + xfit) > lines(spline(xfit. y) > xfit <.22. 201.com/translate_c?hl=pt-BR&ie=UTF-.05) > yfit <. 0. page 51. Mínimos quadrados Maximum likelihood Next: Maximum likelihood . Previous: Generalized linear models .. out$minimum is the SSE.1.

p = c(-50. out$minimum is the negative log-likelihood.8610. 60) The negative log-likelihood to minimize is: > fn <. 53.2 Maximum likelihood Maximum likelihood is a method of nonlinear model fitting that applies even if the errors are not normal.96 SE. 1. . 52.1. y=y) > fit <. or equivalently which minimize the negative log-likelihood.8369. so we can use > df <. Vm.nlm(fn. The data are: > x <. hessian = TRUE) After the fitting. Here is an example from Dobson (1990).20). The method finds the parameter values which maximize the log likelihood.seq(.281e-03 7.57e-05 Residual standard error: 10. 1. We can superimpose the least squares fit on a new plot: > plot(x. To obtain the approximate SEs of the estimates 64 de 99 25/02/2011 10:36 . y)) )) We pick sensible starting values and do the fit: > out <. 108–111. Vm. 56.93 on 10 degrees of freedom Correlation of Parameter Estimates: Vm K 0. K) data: df Vm K 212.. 60) > n <.7242. Vm. K). A 95% confidence interval would be the parameter estimate +/.743 1. 1. Up: Nonlinear least squares and maximum likelihood models 11. 62. y) > xfit <.8839) > y <. 1. The model we have just fitted is the Michaelis-Menten model. Error t value Pr(>|t|) Vm 2.127e+02 6.com/translate_c?hl=pt-BR&ie=UTF-.Uma Introdução ao R http://translate. 28. 1. 62. > sqrt(diag(2*out$minimum/(length(y) . 1.8113.function(p) sum( . 13.2) * solve(out$hessian))) The 2 in the line above represents the number of parameters.7842.7651 Previous: Least squares . 61.7.c( 6.nls(y ~ SSmicmen(x.(y*(p[1]+p[2]*x) .6907. which clearly could also be fit by glm() .412e-02 8..06412146 + xfit) > lines(spline(xfit. yfit)) The standard package stats provides much more extensive facilities for fitting non-linear models by least squares.02.06412123 residual sum-of-squares: 1195. 63.05) > yfit <.7552. K) Parâmetros: Estimate Std. This example fits a logistic model to dose-response data.947e+00 30. 60.68384222 * xfit/(0. df) > fit Nonlinear regression model model: y ~ SSmicmen(x.data. and out$estimate are the maximum likelihood estimates of the parameters.c(1.68370711 0.212. pp. 59.c(59. 18.frame(x=x.24e-11 K 6.1.615 3.449 > summary(fit) Formula: y ~ SSmicmen(x.googleusercontent. 1. 1.n*log(1+exp(p[1]+p[2]*x)) + log(choose(n.

usually one for each determining variable. for example function rlm in package MASS . Function loess is in the standard package stats . There are several functions available for fitting regression models in a way resistant to the influence of extreme outliers in the data.. The results often lead to insights that other data analysis methods tend not to yield.Uma Introdução ao R http://translate. Previous: Statistical models in R .com/translate_c?hl=pt-BR&ie=UTF-. These functions make heavy use of formulae to specify the models. Next: Packages . Less resistant but statistically more efficient methods are available in packages. 65 de 99 25/02/2011 10:36 .. The loess() function fits a nonparametric regression by using a locally weighted regression. Robust regression. The model fitting function is tree() . tree-based models seek to bifurcate the data. This technique aims to construct a regression function from smooth additive functions of the determining variables. Such regressions are useful for highlighting a trend in messy data or for data reduction to give some insight into a large data set. The recommended nlme package provides functions lme() and nlme() for linear and non-linear mixed-effects models. It is possible to use the facilities to display a wide variety of statistical graphs and also to build entirely new types of graph.googleusercontent. Up: Top 12 Graphical procedures Graphical facilities are an important and extremely versatile component of the R environment. Function lqs in the recommended package MASS provides state-of-art algorithms for highly-resistant fits. recursively. Tree models are available in R via the user-contributed packages rpart and tree .1. Local approximating regressions. An extension is Generalized Additive Models . Mixed models. together with code for projection pursuit regression. Rather than seek an explicit global linear model for prediction or interpretation. Tree-based models. we do: > sqrt(diag(solve(out$hessian))) A 95% confidence interval would be the parameter estimate +/. Up: Statistical models in R 11. Additive models. that is linear and non-linear regressions in which some of the coefficients correspond to random effects.96 SE. Previous: Nonlinear least squares and maximum likelihood models . Models are again specified in the ordinary linear model form. at critical points of the determining variables in order to partition the data ultimately into groups that are as homogeneous as possible within. implemented in user-contributed packages gam and mgcv . and as heterogeneous as possible between. but many other generic functions such as plot() and text() are well adapted to displaying the results of a tree-based model fit in a graphical way. Functions avas and ace in package acepack and functions bruto and mars in package mda provide some examples of these techniques in user-contributed packages to R.8 Some non-standard models We conclude this chapter with just a brief mention of some of the other facilities available in R for special regression and data analysis problems.

The plot() function Displaying multivariate data Display graphics Arguments to high-level plotting functions Next: Displaying multivariate data . This manual only describes what are known as `base' graphics..1. using a pointing device such as a mouse. The graphics facilities can be used in both interactive and batch modes. axes. lines and labels. possibly with axes.1 The plot() function One of the most frequently used plotting functions in R is the plot() function. titles and so on. Once the device driver is running. Up: High-level plotting commands 12. an existing plot. labels and titles are automatically generated (unless you request otherwise. but in most cases. Interactive use is also easy because at startup time R initiates a graphics device driver which opens a special graphics window for the display of interactive graphics. or extract information from. This is a generic function: the type of plot produced is dependent on the type or class of the first argument. windows() under Windows and quartz() under Mac OS X. interactive use is more productive. R plotting commands can be used to produce a variety of graphical displays and to create entirely new kinds of display.Uma Introdução ao R http://translate. Interactive graphics functions allow you interactively add information to. it is useful to know that the command used is X11() under UNIX.) High-level plotting commands always start a new plot. Plotting commands are divided into three basic groups: High-level plotting functions create a new plot on the graphics device. Where appropriate. labels. Low-level plotting functions add more information to an existing plot. R maintains a list of graphical parameters which can be manipulated to customize your plots. 66 de 99 25/02/2011 10:36 ..googleusercontent. Up: Graphics 12. erasing the current plot if necessary. In addition. There is a recommended package lattice which builds on grid and provides ways to produce multi-panel plots akin to those in the Trellis system in S. Previous: Graphics . Although this is done automatically. A separate graphics sub-system in package grid coexists with base – it is more powerful but harder to use.com/translate_c?hl=pt-BR&ie=UTF-.1 High-level plotting commands High-level plotting functions are designed to generate a complete plot of the data passed as arguments to the function. such as extra points. High-level plotting commands Low-level plotting commands Interacting with graphics Using graphics parameters Graphics parameters Os drivers de dispositivo Dynamic graphics Next: Low-level plotting commands . Previous: High-level plotting commands .

it produces a plot of imaginary versus real parts of the vector elements.2 Displaying multivariate data R provides two very useful functions for representing multivariate data. plot( x ) If x is a time series. that is. expr is a list of object names separated by ` + ' (eg.. x. y is any object. The same effect can be produced by supplying one argument (second form) as either a list containing two elements x and y or a two-column matrix. The third form plots y against every object named in expr . The number and position of intervals can be controlled with given. it is divided into a number of conditioning intervals and for each interval a is plotted against b for values of c within the interval. plot( f ) plot( f .. The coplot() and pairs() function both take an argument panel= which can be used to customize the type of plot which appears in each panel. y is a numeric vector. plot( x . The first form generates a bar plot of f . a + b + c ).com/translate_c?hl=pt-BR&ie=UTF-.smooth() . Previous: The plot() function . the command > pairs(X) produces a pairwise scatterplot matrix of the variables defined by the columns of X . If a and b are numeric vectors and c is a numeric vector or factor object (all of the same length).y) xy ) If x and y are vectors. The default is points() to produce a scatterplot but by supplying some other low-level graphics function of two vectors x and y as the value of panel= you can produce any type of plot you wish.intervals() is useful for selecting intervals. If x is a numeric vector. y ) f is a factor object.googleusercontent. plot( plot( Next: Display graphics . this produces a time-series plot. Up: High-level plotting commands 12. The first two forms produce distributional plots of the variables in a data frame (first form) or of a number of named objects (second form). If X is a numeric matrix or data frame. When three or four variables are involved a coplot may be more enlightening.Uma Introdução ao R http://translate.values= argument to coplot() —the function co. If x is a complex vector. the second form produces boxplots of y for each level of f . this simply means that a is plotted against b for every level of c . plot( df ) plot(~ expr ) plot( y ~ expr ) df is a data frame. When c is numeric. it produces a plot of the values in the vector against their index in the vector. If c is a factor. every column of X is plotted against every other column of X and the resulting n(n-1) plots are arranged in a matrix with plot scales constant over the rows and columns of the matrix.1. 67 de 99 25/02/2011 10:36 . An example panel function useful for coplots is panel. You can also use two given variables with a command like > coplot(a ~ b | c + d) which produces scatterplots of a against b for every joint conditioning interval of c and d . then the command > coplot(a ~ b | c) produces a number of scatterplots of a against b for given values of c . y ) produces a scatterplot of y against x .

type= The type= argument controls the type of plot produced.1. superimposing the plot on the current plot (some functions only). as follows: add=TRUE Forces the function to act as a low-level graphics function. .com/translate_c?hl=pt-BR&ie=UTF-. y.. nclass= hist(x..Uma Introdução ao R http://translate. . For example it allows easy visual selection of all data entries with values lying in specified ranges. the bars represent relative frequencies divided by bin width instead of counts. the breakpoints can be specified exactly with the breaks= argument. means include axes.) persp(x. axes=TRUE . Up: High-level plotting commands 12. log="x" log="y" log="xy" Causes the x. z. z.... as follows: type="p" Plot individual points (the default) 68 de 99 25/02/2011 10:36 .) Plots of three variables. . axes=FALSE Suppresses generation of axes—useful for adding your own custom axes with the axis() function. hist(x) hist(x. Previous: Display graphics . Alternatively. y. The default. y) Distribution-comparison plots. Alguns exemplos são: qqnorm(x) qqline(x) qqplot(x. A sensible number of classes is usually chosen. dotchart(x.. .googleusercontent. Previous: Displaying multivariate data . In a dotchart the y-axis gives a labelling of the data in x and the x-axis gives its value. If the probability=TRUE argument is given. z. types of plot. the contour plot draws contour lines to represent the value of z .) contour(x.. Up: High-level plotting commands 12.. but a recommendation can be given with the nclass= argument.4 Arguments to high-level plotting functions There are a number of arguments which may be passed to high-level graphics functions.. breaks= n) b .3 Display graphics Other high-level graphics functions produce different types of plots. This will work for many. The first form plots the numeric vector x against the expected Normal order scores (a normal scores plot) and the second adds a straight line to such a plot by drawing a line through the distribution and data quartiles. The image plot draws a grid of rectangles using different colours to represent the value of z . .1. y or both axes to be logarithmic. The third form plots the quantiles of x against those of y to compare their respective distributions. Next: Arguments to high-level plotting functions .. but not all.) Produces a histogram of the numeric vector x .) image(x. Constructs a dotchart of the data in x . y... and the persp plot draws a 3D surface.

b) abline(h= y ) 69 de 99 25/02/2011 10:36 . y[i]) . the bottom. In this case. as specified by the character vector names for the points. y. usually the names of the objects used in the call to the high-level plotting function. y. In the first form. y) Adds points or connected lines to the current plot. The default is 1:length(x) . Up: Graphics 12. and the text() function supplies special characters. abline(a. Note : This function is often used in the sequence > plot(x. Ideal for creating plots with subsequent low-level graphics functions. Normally labels is an integer or character vector in which case labels[i] is plotted at point (x[i].2 Low-level plotting commands Sometimes the high-level plotting functions don't produce exactly the kind of plot you desire. labels. type="n"). placed at the top of the plot in a large font.com/translate_c?hl=pt-BR&ie=UTF-. y. .googleusercontent. xlab= ylab= Next: Interacting with graphics . However axes are still drawn (by default) and the coordinate system is set up according to the data. placed just below the x-axis in a smaller font. lines or text) to the current plot.) text(x. type="n" No plotting at all. low-level plotting commands can be used to add extra information (such as points. the top of the vertical defines the point. plot() 's type= argument can also be passed to these functions (and defaults to "p" for points() and "l" for lines() . names) The graphics parameter type="n" suppresses the points but sets up the axes. Previous: High-level plotting commands .Uma Introdução ao R http://translate.) Add text to a plot at points given by x. y) lines(x. sub= string Sub-title. Use these arguments to change the default labels. string string Axis labels for the x and y axes. main= string Figure title. type="l" Plot lines type="b" Plot points connected by lines ( both ) type="o" Plot points overlaid by lines type="h" Plot vertical lines from points to the zero axis ( high-density ) type="s" type="S" Step-function plots. y .. Some of the more useful low-level plotting functions are: points(x. in the second. text(x....

.obj may be list with a coefficients component of length 2 (such as the result of model-fitting functions. axis . in that order. or title . lty= v ) Line styles legend( . Plotting characters.. line styles.com/translate_c?hl=pt-BR&ie=UTF-.. as follows: legend( . lwd= v ) Line widths legend( . it is also sufficient to supply a single argument being a list with elements named x and y . Mathematical annotation Hershey vector fonts Next: Hershey vector fonts . pch= v ) Plotting characters (character vector) title(main. col= v ) Colors in which points or lines will be drawn legend( .. Useful for adding custom axes after calling plot() with the axes=FALSE argument.) Draws a polygon defined by the ordered vertices in ( x . This can be achieved in R by specifying an expression rather than a character string in any one of text .1 Mathematical annotation In some cases. legend. Up: Low-level plotting commands 12. . sub) Adds a title main to the top of the current sub at the bottom in a smaller font. fill= v ) Colors for filled boxes legend( . Similarly a matrix with two columns is also valid input. axis(side. Previous: Low-level plotting commands . For example. counting clockwise from the bottom. it is useful to add mathematical symbols and formulae to a plot. polygon(x. mtext . y. h= y may be used to specify y-coordinates for the heights of horizontal lines to go across a plot. y ) and (optionally) shade it in with hatch lines. or fill it if the graphics device allows the filling of figures.) which are taken as an intercept and slope.2. Also lm. Coordinates are given in terms of user coordinates which are defined by the previous high-level graphics command and are chosen based on the supplied data. abline(v= x ) abline( lm. and v= x similarly for the x-coordinates for vertical lines. Where x and y arguments are required... and tick positions and labels... . are identified with the labels in the character vector legend . colors etc.) Adds a legend to the current plot at the specified position.googleusercontent. Low-level plotting functions usually require some positioning information (eg. y. In this way functions such as locator() (see below) may be used to specify positions on a plot interactively. the following code draws the formula for the Binomial 70 de 99 25/02/2011 10:36 . At least one other argument v (a vector the same length as legend ) with the corresponding values of the plotting unit must also be given. x and y coordinates) to determine where to place the new plot elements.Uma Introdução ao R http://translate. legend(x.) Other arguments control the positioning of the axis within or beside the plot.obj ) Adds a line of slope b and intercept a to the current plot..) plot in a large font and (optionally) a sub-title Adds an axis to the current plot on the side given by the first argument (1 to 4..

2 Hershey vector fonts It is possible to specify Hershey vector fonts for rendering text when using the text and contour functions. probability function: > text(x. including tables of Hershey characters can be obtained from within R using the commands: > help(Hershey) > demo(Hershey) > help(Japanese) > demo(Japanese) Next: Using graphics parameters . For example. adj=0) may be useful. q^{nx}))) More information. the command > text(locator(1). p^x. labels) Allow the user to highlight any of the points defined by x and y (using the left mouse 71 de 99 25/02/2011 10:36 . or another mouse button is pressed. x). to place some informative text near an outlying point.) identify(x.3 Interacting with graphics R also provides functions which allow users to extract or add information to a plot using a mouse. Up: Graphics 12. atop(n. More information.Uma Introdução ao R http://translate.2. ( locator() will be ignored if the current device.com/translate_c?hl=pt-BR&ie=UTF-. especially on a computer screen. including a full listing of the features available can obtained from within R using the commands: > help(plotmath) > example(plotmath) > demo(plotmath) Previous: Mathematical annotation . locator() returns the locations of the points selected as a list with two components x and y . y. It is particularly useful for interactively selecting positions for graphic elements such as legends or labels when it is difficult to calculate in advance where the graphic should be placed. locator() is usually called with no arguments. Hershey fonts provide certain symbols that may not be available in the standard fonts. type) Waits for the user to select locations on the current plot using the left mouse button. ")"). There are three reasons for using the Hershey fonts: Hershey fonts can produce better output.. there are zodiac signs. such as postscript does not support interactive pointing. cartographic symbols and astronomical symbols. Previous: Low-level plotting commands . Up: Low-level plotting commands 12. In particular. expression(paste(bgroup("(". the default is no plotting. "Outlier". The type argument allows for plotting at the selected points and has the same effect as for high-level graphics commands. for rotated and/or small text.googleusercontent. This continues until n (default 512) points have been selected. y.. Hershey fonts provide cyrillic and japanese (Kana and Kanji) characters. The simplest of these is the locator() function: locator(n.

or temporarily.. y) coordinates in two numeric vectors x and y . The par() function Arguments to graphics functions Next: Arguments to graphics functions . For example. sets the values of the named graphics 72 de 99 25/02/2011 10:36 . par() Without arguments. or disable marking altogether with the plot = FALSE argument. Returns the indices of the selected points when another button is pressed. "lty")) With a character vector argument. and each device has a default set of parameters when initialized. but simply allows the user to move the mouse pointer and click the left mouse button near a point. customize almost every aspect of the display using graphics parameters . R's defaults do not always produce exactly that which is required. Previous: Using graphics parameters . its position in the x / y vectors) plotted nearby. which controls colors.) and a value (a color number.. y) > identify(x. Next: Graphics parameters . lty=2) With named arguments (or a single list argument). as a list. figure arrangement and text justification among many others. Every graphics parameter has a name (such as ` col '.googleusercontent. returns only the named graphics parameters (again. you can use these indices to extract the selected points from the original vectors x and y . par(c("col".1 Permanent changes: The par() function The par() function is used to access and modify the list of graphics parameters for the current graphics device. affecting all graphics functions which access the current device. particularly for presentation or publication purposes. we may wish the user to select some observation of interest from a graphical display and then manipulate that observation in some way.com/translate_c?hl=pt-BR&ie=UTF-. however. identify() returns the indices of the selected points.) par(col=4. If there is a point near the mouse pointer it will be marked with its index number (that is. we could use the identify() function as follows: > plot(x.4. You can. rather than their positions. Graphics parameters can be set in two ways: either permanently. Sometimes we want to identify particular points on a plot. Given a number of (x. button) by plotting the corresponding component of labels nearby (or the index number of the point if labels is absent). R maintains a list of a large number of graphics parameters which control things such as line style. y) The identify() functions performs no plotting itself. Alternatively. Previous: Interacting with graphics . returns a list of all graphics parameters and their values for the current device. affecting only a single graphics function call.4 Using graphics parameters When creating graphics. you could use some informative string (such as a case name) as a highlight by using the labels argument to identify() . When the process is terminated (see above). Up: Using graphics parameters 12.) A separate list of graphics parameters is maintained for each active device. colors.Uma Introdução ao R http://translate. for example. Up: Graphics 12.

do some plotting. this is not implemented entirely consistently and it is sometimes necessary to set and reset graphics parameters using par() . Next: Device drivers . > oldpar <. value is a typical value you might use when setting the parameter. y. pch="+") produces a scatterplot using a plus sign as the plotting character. This is often undesirable behavior—usually we want to set some graphics parameters. This has the same effect as passing the arguments to the par() function. and returns the original values of the parameters as a list..par(col=4.2 Temporary changes: Arguments to graphics functions Graphics parameters may also be passed to (almost) any graphics function as named arguments. this is provided as a somewhat more detailed alternative. which will be used by all graphics functions unless an alternative value is given. and restoring the initial values when plotting is complete. in the sense that all future calls to graphics functions (on the current device) will be affected by the new value. except that the changes only last for the duration of the function call. You can think of setting graphics parameters in this way as setting “default” values for the parameters.5 Graphics parameters list The following sections detail many of the commonly-used graphical parameters. name is the name of the parameter. yaxt 73 de 99 25/02/2011 10:36 .Uma Introdução ao R http://translate. plotting commands . > par(oldpar) To save and restore all settable 23 graphical parameters use > oldpar <. You can restore the initial values by saving the result of par() when making changes... that is.par(no. Por exemplo: > plot(x. plotting commands . lty=2) .. > par(oldpar) Previous: The par() function .com/translate_c?hl=pt-BR&ie=UTF-. Unfortunately.googleusercontent. and then restore the original values so as not to affect the user's R session.4. Note that axes is not a graphics parameter but an argument to a few plot methods: see xaxt and ... parameters.readonly=TRUE) . Note that calls to par() always affect the global values of graphics parameters. Graphics parameters will be presented in the following form: name = value A description of the parameter's effect.. the argument name to use in calls to par() or a graphics function. Previous: Using graphics parameters . Setting graphics parameters with the par() function changes the value of the parameters permanently .. Up: Graphics 12. The R help documentation for the par() function provides a more concise summary. Up: Using graphics parameters 12.. without changing the default plotting character for future plots.. even when par() is called from within a function.

axis font. Alternative line styles are not supported on all graphics devices (and vary on those that do) but line type 1 is always a solid line. A number from the current palette (see ?palette ) or a named colour. line type 0 is always invisible. If possible. as.sub The color to be used for axis annotation.5 means to center horizontally about the plotting position.1 Graphical elements R plots are made up of points. lines. a specialized plotting symbol is produced.. Graphical elements Axes and tick marks Figure margins Multiple figure environment Next: Axes and tick marks . 4 to bold italic and 5 to a symbol font (which include Greek letters).googleusercontent. adj=-0.com/translate_c?hl=pt-BR&ie=UTF-.. but it is usually a circle.main col. col=2 Colors to be used for points. Not all devices support this.sub The font to be used for axis annotation.1 Justification of text relative to the plotting position. 2 to bold face. main and sub-titles. text and polygons (filled regions.main font.) Graphical parameters exist which control how these graphical elements are drawn. The actual value is 74 de 99 25/02/2011 10:36 . respectively. Up: Graphics parameters 12. lwd=2 Line widths. pch can be a character or a number in the range 32:255 representing a character in the current font. use the command > legend(locator(1). 1 means right justify and 0. text. Desired width of lines. or some combination of both. lines. main and sub-titles. lty=2 Line types.lab col. font=2 An integer which specifies which font to use for text. pch = 0:25) Those from 21 to 25 may appear to duplicate earlier symbols. etc.5. respectively.axis col. Plotted points tend to appear slightly above or below the appropriate position unless you use ". To see what the symbols are. In addition. x and y labels. Affects axis lines as well as lines drawn with lines() .Uma Introdução ao R http://translate. x and y labels. 3 to italic.character(0:25). 0 means left justify. which produces centered points. and some have restrictions on the widths that can be used. device drivers arrange so that 1 corresponds to plain text. in multiples of the “standard” line width.lab font. font. filled regions and images. but can be coloured in different ways: see the help on points and its examples. col. and line types 2 and onwards are dotted or dashed lines. pch=4 When pch is given as an integer between 0 and 25 inclusive. Previous: Graphics parameters . as follows: pch="+" Character to be used for plotting points." as the plotting character. The default varies with graphics drivers.

3 Figure margins A single plot in R is known as a figure and comprises a plot region surrounded by margins (possibly containing axis labels. Up: Graphics parameters 12. as a fraction of the size of the plotting region. in characters (including the decimal point.main cex. in text lines. Previous: Axes and tick marks . cex.2 Axes and tick marks Many of R's high-level plots have axes. respectively. x and y labels.) and (usually) bounded by the axes themselves.. With styles "i" (internal) and "r" (the default) tick marks always fall within the range of the data.-1. so a value of -0. respectively.) Choosing a too-small value for this parameter may result in all tick labels being rounded to the same number! las=1 Orientation of axis labels. etc. A value of 1 gives grid lines. the tick marks (which mark off unit divisions along the axis line) and the tick labels (which mark the units. Next: Figure margins . lab=c(5.Uma Introdução ao R http://translate. negative numbers inside.01 Length of tick marks. Axes have three main components: the axis line (line style controlled by the lty graphics parameter).) These components can be customized with the following graphics parameters. 1 means always horizontal.) Next: Multiple figure environment . (S has other styles not implemented in R. 1. 7. and the final component is the distance from the axis position to the axis line (usually zero). When tck is small (less than 0.01 and mgp=c(1. cex=1.googleusercontent. xaxs="r" yaxs="i" Axis styles for the x and y axes. The second component is the distance to the tick labels. Negative values give tick marks outside the plotting region.. tck=0.5 Character expansion. Positive numbers measure outside the plot region.lab cex. The value is the desired size of text characters (including plotting characters) relative to the default text size. The third number is the desired length of axis labels. Up: Graphics parameters 12. and 2 means always perpendicular to the axis.1 leaves a gap of 10% of the text width between the text and the plotting position. however style "r" leaves a small amount of space at the edges. Graphics parameters controlling figure layout include: 75 de 99 25/02/2011 10:36 . the proportion of text that appears to the left of the plotting position. 0) Positions of axis components. main and sub-titles.0) for internal tick marks. The first component is the distance from the axis label to the axis position. Use tck=0.axis cex.com/translate_c?hl=pt-BR&ie=UTF-.5. 0 means always parallel to axis. 12) The first two numbers are the desired number of tick intervals on the x and y axes respectively. and you can construct axes yourself with the low-level axis() graphics function. mgp=c(3.sub The character expansion to be used for axis annotation. Previous: Graphical elements .5.5. titles.5) the tick marks on the x and y axes are forced to be the same size.

2. the default is chosen without regard to the size of the device surface: for example.5. 2) mfrow=c(2. 3. the figure shows the page after four plots have been drawn.66. mfrow fills by rows.2) . bottom and top edges respectively. the last two are the number of rows and columns in the multiple figure array. Up: Graphics parameters 12.8. The layout in the Figure could have been created by setting mfrow=c(3. and the array of figures is optionally surrounded by an outer margin . 76 de 99 25/02/2011 10:36 .83: if there are three or more of either rows or columns. using the postscript() driver with the height=4 argument will result in a plot which is about 50% margin unless mar or mai are set explicitly. Each figure has its own margins. 9. top and right margins. use new=TRUE as well (unlike S). the reduction factor is 0. 0) omi=c(0. 1) Similar to mai . as shown in the following figure. The first value is the number of rows. 2. as a percentage of the page measured from the bottom left corner. 4)/10 Position of the current figure on the page. Values are the positions of the left. If you want to add a figure to a current page. and neither is the top margin if no title is being used. respectively. Set this parameter to jump between figures in the array. right. oma=c(2. 0.. and mai are equivalent in the sense that setting one changes the value of the other. 2) Position of the current figure in a multiple figure environment. 0. the right-hand margin is rarely needed. The first two numbers are the row and column of the current figure. The example value would be for a figure in the bottom right of the page. fig=c(4. 0) Size of outer margins.4 Multiple figure environment R allows you to create an n by m array of figures on a single page. The graphical parameters relating to multiple figures are as follows: mfcol=c(3. The bottom and left margins must be large enough to accommodate the axis and tick labels. In a layout with exactly two rows and columns the base size is reduced by a factor of 0. 0) Widths of the bottom.. Like mar and mai . mar=c(4. Previous: Figure margins . mai=c(1. You can even use different values for the last two numbers than the true values for unequally-sized figures on the same page. measured in inches. 0. 1.5.Uma Introdução ao R http://translate.5. however this may not be enough when many figures share the same page.com/translate_c?hl=pt-BR&ie=UTF-. When multiple figures are in use (see below) the margins are reduced. 0. Setting either of these can reduce the base size of symbols and text (controlled by par("cex") and the pointsize of the device).googleusercontent. 2. the first measures in text lines and the second in inches. The only difference between these two parameters is that setting mfcol causes figures to be filled by column. mar except the measurement unit is text lines. Set this parameter for arbitrary positioning of figures within a page. the second is the number of columns. Furthermore. 3. The default values chosen for this parameter are often too large. mfg=c(2. 4) Set the size of a multiple figure array. 0. left. starting with the bottom margin and working clockwise.

which can also be included into PDF files.screen() and layout() functions.) When you have finished with a device. pdf() Produces a PDF file. as well as by the grid and lattice packages. png() Produces a bitmap PNG file. Text can be added to the outer margins with the mtext() function with argument outer=TRUE . (Not always available: see its help page.” for example) into a form that the particular device can understand.. Outer margins are particularly useful for page-wise titles. Up: Device drivers 12. best used for image plots. This is done by starting a device driver .6. or creating PostScript graphics files.Uma Introdução ao R http://translate. Some commonly-used device drivers are: X11() For use with the X11 window system on Unix-alikes windows() For use on Windows quartz() For use on Mac OS X postscript() For printing on PostScript printers. etc.6 Device drivers R can generate graphics (of varying levels of quality) on almost any type of display or printing device. however. There are no outer margins by default. (Not always available: see its help page.) PostScript diagrams for typeset documents Multiple graphics devices Next: Multiple graphics devices .off() This ensures that the device finishes cleanly. R needs to be informed what type of device it is dealing with. Device drivers are started by calling a device driver function. Up: Graphics 12. be sure to terminate the device driver by issuing the command > dev. There is one such function for every device driver: type help(Devices) for a list of them all. for example in the case of hardcopy devices this ensures that every page is completed and has been sent to the printer. More complicated arrangements of multiple figures can be produced by the split.googleusercontent. For example. The purpose of a device driver is to convert graphical instructions from R (“draw a line. issuing the command > postscript() causes all future graphics output to be sent to the printer in PostScript format. Before this can begin.1 PostScript diagrams for typeset documents 77 de 99 25/02/2011 10:36 .com/translate_c?hl=pt-BR&ie=UTF-.) jpeg() Produces a bitmap JPEG file. (This will happen automatically at the normal end of a session. so you must create them explicitly using oma or omi . Previous: Graphics parameters .. Previous: Device drivers . Next: Dynamic graphics . however.

ps". to which graphics output will be sent. This unusual notation stems from S-compatibility: it really means that the output will be a single page (which is part of the EPSF specification). This works best when encapsulated PostScript is produced: R always produces conformant output. Up: Device drivers 12. Each new call to a device driver function opens a new graphics device. onefile=FALSE. width=6. the command > postscript("file. thus extending by one the device list. you may store the graphics in PostScript format in a file of your choice. pointsize=10) will produce a file containing PostScript code for a figure five inches high.metafile() [Windows] quartz() [Mac OS X] postscript() pdf() png() jpeg() tiff() bitmap() .printer() win. The plot will be in landscape orientation unless the horizontal=FALSE argument is given. Thus to produce a plot for inclusion use something like > postscript("plot1.6.. and their meanings are as follows: X11() [UNIX] windows() win. and you can control the size of the graphic with the width and height arguments (the plot will be scaled as appropriate to fit these dimensions.eps". perhaps for inclusion in a document.prev() Returns the number and name of the graphics device next to.. This is the case even if the file was only created earlier in the same R session. Many usages of PostScript output will be to incorporate the figure in another document.com/translate_c?hl=pt-BR&ie=UTF-.2 Multiple graphics devices In advanced use of R it is often useful to have several graphics devices in use at the same time.) For example. dev.googleusercontent. they form a numbered sequence with names giving the kind of device at any position. or previous to the current device. The device at position 1 on the list is always the null device which does not accept graphics commands at all. dev. and this is known as the current device . respectively.Uma Introdução ao R http://translate. it will be overwritten. but only marks the output as such when the onefile=FALSE argument is supplied. This device becomes the current device. By passing the file argument to the postscript() device driver function.. Of course only one graphics device can accept graphics commands at any one time. height=8. It is important to note that if the file named in the command already exists. When multiple devices are open.next() dev.. The main commands used for operating with multiple devices. 78 de 99 25/02/2011 10:36 . pointsize=10) Previous: PostScript diagrams for typeset documents . horizontal=FALSE. height=5.list() Returns the number and name of all active devices. horizontal=FALSE.

and to aid package developers.packages() and update.org/ and these can be accessed from R via the package rggobi . such as postscript devices. but the copied device is immediately closed. such as printing hardcopies. except the null device. this will either print the file immediately or correctly complete the file for later printing. such as postscript . Up: Graphics 12. eg rotating point clouds or to “brushing” (interactively highlighting) points. if needed.copy(device. Here.ggobi. depending on how the device was initiated.. use a command like > library(boot) Users connected to the Internet can use the install.packages() functions (available through the Packages menu in the Windows and RAqua GUIs..ggobi. For some devices. the boot package containing functions from Davison & Hinkley (1997)).off( k ) Terminate the graphics device at point k of the device list.off() Terminate all graphics devices on the list. package rgl provides ways to interact with 3D plots. .. '.. are immediately performed. extensive dynamic graphics facilities are available in the system GGobi by Swayne. Previous: Device drivers .org /rggobi . dev. k) Can be used to change the current graphics device to the one at position k of the device list.print(device.googleusercontent. Returns the number and label of the device.Uma Introdução ao R http://translate... The process of developing packages is described in Creating R packages . This is done both for efficiency (the full list would take more memory and would take longer to search than a subset). Next: A sample session . Previous: Graphics . dev. Only when a package is loaded are its contents available. which= k ) Make a copy of the device k .set(which= graphics. described at http://www. which= k ) dev. dev. To see which packages are currently loaded. who are protected from name clashes with other code. To load a particular package (eg. we will describe them from a user's point of view. use 79 de 99 25/02/2011 10:36 . specified by ' . However. To see which packages are installed at your site.. dev. Cook and Buja available from http://www.. see Installing packages ) to install and update packages. Up: Top 13 Packages All R functions and datasets are stored in packages . so that end actions. with extra arguments. Also. for example of surfaces..7 Dynamic graphics R does not have builtin capabilities for dynamic or interactive graphics. issue the command > library() with no arguments.com/translate_c?hl=pt-BR&ie=UTF-. . Here device is a device function..print is similar.

for a complete list.Uma Introdução ao R http://translate. Up: Packages 13. because it is defined in the base package.start () to start the HTML help system. the transpose function will always be available as base::t . use > Help. 80 de 99 25/02/2011 10:36 . There are two operators that work with namespaces.. Up: Packages 13. Namespaces prevent the user's definition from taking precedence. and they provide a way to refer to an object within a particular package. See R packages .org/ and its mirrors). They should be automatically available in any R installation.3 Namespaces Packages can have namespaces . The R FAQ contains a list that was current at the time of release. Some of these packages implement specialized statistical methods. t() is the transpose function in R. Up: Packages 13. pacotes padrão Contributed packages and CRAN Namespaces Next: Contributed packages and CRAN . and other repositories such as Bioconductor ( http://www.googleusercontent.org/ ).bioconductor. and currently all of the base and recommended packages do except the datasets package. written by many different authors. but the collection of available packages changes frequently.1 Standard packages The standard (or base ) packages are considered part of the R source code. and breaking every function that tries to transpose a matrix. others give access to data or hardware. Some (the recommended packages) are distributed with every binary distribution of R. and the datasets and standard statistical and graphical functions that are described in this manual. Only functions that are exported from the package can be retrieved in this way.. Next: Namespaces . Previous: Contributed packages and CRAN . They contain the basic functions that allow R to work. they prevent functions from breaking when a user (or other package writer) picks a name that clashes with one in the package. Most are available for download from CRAN ( http://CRAN. and then navigate to the package listing in the Reference section.R-project. Previous: Standard packages . Some packages may be loaded but not available on the search list (see Namespaces ): these will be included in the list given by > loadedNamespaces() To see a list of all available help topics in an installed package.2 Contributed packages and CRAN There are hundreds of contributed packages for R. Namespaces do three things: they allow the package writer to hide functions and data that are meant only for internal use. For example. In the example above. Previous: Packages . The double-colon operator :: selects definitions from a particular namespace. > search() to display the search list. but users might define their own function named t . and others are designed to complement textbooks.com/translate_c?hl=pt-BR&ie=UTF-.

Uma Introdução ao R http://translate. Next: Invoking R . With y to the left of the tilde.and y-coordinates. You should briefly explore the features of this facility with the mouse. ls() See which R objects are now in the R workspace. and look at it.data. the prompt on the left hand side will not be shown to avoid confusion. The colon operators described above will also cause automatic loading of the associated package. fm <.rnorm(50) y <.rnorm(x) Generate two pseudo-random normal vectors of x. data=dummy.. A `weight' vector of standard deviations. y= x + rnorm(x)*w) dummy Make a data frame of two columns. (Clean up). .lm(y ~ x.googleusercontent. and loading one may cause others to be automatically loaded. plot(x. Many features of the system will be unfamiliar and puzzling at first. x <. Iconify the help window and move on to the next part. rm(x. The triple-colon operator ::: may be seen in a few places in R code: it acts like the double-colon operator but also allows access to hidden objects.start() Start the HTML interface to on-line help (using a web browser available at your machine). we can do a weighted regression.1 + sqrt(x)/2 .. Up: Top Appendix AA sample session The following session is intended to introduce to you some features of the R environment by using them. y) Remove objects no longer needed. dummy <.1:20 Make x = (1. (Within R. $ R Start R as appropriate for your platform. When packages with namespaces are loaded automatically they are not added to the search list. Login.) help. w <. but this puzzlement will soon disappear. Previous: Packages . weight=1/w^2) summary(fm1) Since we know the standard deviations. A graphics window will appear automatically. x and y.lm(y ~ x. data=dummy) summary(fm) Fit a simple linear regression and look at the analysis. Packages are often inter-dependent. fm1 <.frame(x=x. start your windowing system. Users are more likely to use the getAnywhere() function... 2. y) Plot the points in the plane. The R program begins. we are modelling y dependent on x.com/translate_c?hl=pt-BR&ie=UTF-. attach(dummy) 81 de 99 25/02/2011 10:36 . which searches multiple packages. 20). x <. with a banner.

1. mm <. This dataset is available in the morley object. (Not very useful here. xlab="Fitted values" .factor(mm$Run) Change Expt and Run into attach(mm) factors. lrf <. fm <. and compare using a formal analysis of variance. abline(coef(fm)) Unweighted regression line. The next section will look at data from the classical experiment of Michaelson and Morley to measure the speed of light. .") Compare the five experiments with simple boxplots. slope 1). detach() rm(fm.. 82 de 99 25/02/2011 10:36 . plot(fitted(fm).googleusercontent. with `runs' and `experiments' as factors. lrf$y) Add in the local regression. Você pode vê-lo? qqnorm(resid(fm).system. "morley. abline(0.Uma Introdução ao R http://translate. xlab="Experiment No. main="Residuals Rankit Plot") A normal scores plot to check for skewness. col = "red") Weighted regression line. dummy) Clean up again.update(fm. Look at the file. ylab="Residuals" . abline(coef(fm1). y) Standard point plot.table function. fm1. x. fm) Fit the sub-model omitting `runs'.. There are five experiments (column Expt ) and each has 20 runs (column Run ) and sl is the recorded speed of light.com/translate_c?hl=pt-BR&ie=UTF-. kurtosis and outliers.Run) anova(fm0. suitably coded. y) Make a nonparametric local regression function. resid(fm). lty=3) The true regression line: (intercept 0.lowess(x. package="datasets") filepath Get the path to the data file. but we will read it to illustrate the read. data=mm) summary(fm) Analyze as a randomized block. detach() Remove data frame from the search path. ~ . Speed. xlab="Fitted values" .file("data".table(filepath) mm Read in the Michaelson and Morley data as a data frame. plot(x. fm0) Clean up before moving on. Make the columns in the data frame visible as variables. . fm0 <. main="Residuals vs Fitted") A standard regression diagnostic plot to check for heteroscedasticity.tab" .factor(mm$Expt) mm$Run <. Make the data frame visible at position 3 (the default). file. plot(Expt.) rm(fm.read. and look at it.aov(Speed ~ Run + Expt. filepath <. main="Speed of Light Data".show(filepath) Opcional. ylab="Residuals" . mm$Expt <. lrf. lines(x.

Up: Top 83 de 99 25/02/2011 10:36 .outer(x. f. fa. One method would be to take complex numbers with standard normal real and imaginary parts .1). y) cos(y)/(1 + x^2)) f is a square matrix. . pi]. f.1). 1/w. w <. with rows and columns indexed by x and y respectively... nlevels=15. but the distribution is not uniform. Previous: A sample session .googleusercontent.. nlevels=15) Make a contour plot. y is the same. y. f) image(x.exp(1i*th) 1i is used for the complex number i... This should be a circle. th <. xlab="x". We now look at some more graphical features: contour and image plots.seq(-pi. function(x. objects().par(no.. w <..(ft(f))/2 fa is the “asymmetric part” of f. also. y. f) contour(x. w <. add=TRUE) Make a contour map of f. pch="+".x x is a vector of 50 equally spaced values in the interval [-pi\.com/translate_c?hl=pt-BR&ie=UTF-. y. type="l") Plotting complex arguments means plot imaginary versus real parts. rm(th. par(pty="s") plot(z. y. pch="+". contour(x. y..xlab="x".sqrt(runif(100))*exp(2*pi*runif(100)*1i) plot(w. and restore the old graphics parameters. y. fa <. y.ifelse(Mod(w) > 1. q() Quit the R program.rnorm(100) + rnorm(100)*1i Suppose we want to sample points within the unit circle.. and for an exploratory session like this. Next: The command-line editor . contour(x... w) . R can do complex arithmetic. rm(x. plot(w. ylab="y") lines(z) The second method uses the uniform distribution. you probably do not want to save it. xlim=c(-1. ( t() is transpose).seq(-pi. of values of the function cos(y)/(1 + x^2). par(oldpar) .. oldpar <. z) Clean up again. (of which you can get hardcopies if you wish). ylim=c(-1.Uma Introdução ao R http://translate. ylab="y") lines(z) All points are inside the unit circle. len=100) z <.. f <.1). xlim=c(-1.1). pi. . len=50) y <. x <.readonly = TRUE) par(pty="s") Save the plotting parameters and set the plotting region to “square”. ylim=c(-1. pi. You will be asked if you want to save the R workspace. fa) . and to map any outside the circle onto their reciprocal. image(x. fa) Make some high density image plots.. add in more lines for more detail. and clean up before moving on. w. The points should now look more evenly spaced over the disc.

or.Uma Introdução ao R http://translate.1 Invoking R from the command line When working in UNIX or at a command line in Windows. Finally. R searches for user and site files to process for setting environment variables. a file called . The startup mechanism is as follows (see also the on-line help for topic ' Startup ' for more information.) Variables you might want to set include R_PAPERSIZE (the default paper size). R searches for a user profile and sources it. Then R searches for the site-wide startup profile unless the command line option --no-site-file was given. R_HOME /etc/Renviron.Last which is executed at the end of the R session) can be defined in the appropriate startup profiles.com/translate_c?hl=pt-BR&ie=UTF-. as a wrapper to various R tools (eg.. If that variable is unset.Renviron in the current or in the user's home directory (in that order) are searched for. files . In addition. Users will not normally need to use these unless they are trying to limit the amount of memory used by R. the command ' R ' can be used both for starting the main R program in the form R [ options ] [ < infile ] [ > outfile ]. R accepts the following command-line options.RData . The user file is the one pointed to by the environment variable R_ENVIRON_USER if this is set.site is used if this exists. if this is unset.site is used (if it exists). It also loads a saved image from . Up: Invoking R B. This function (as well as . The name of the site file is the one pointed to by the environment variable R_ENVIRON . via the R CMD interface. The name of this file is taken from the environment variable R_PROFILE_USER . You need to ensure that either the environment variable TMPDIR is unset or it points to a valid place to create temporary files and directories. it is executed. Then. there are options for controlling the memory available to the R process (see the on-line help for topic ' Memory ' for more information). for processing files in R documentation format or manipulating add-on packages) which are not intended to be called “directly”. the default R_HOME /etc/Rprofile. R_PRINTCMD (the default print command) and R_LIBS (specifies the list of R library trees searched for add-on packages). Appendix B Invoking R Invoking R from the command line Invoking R under Windows Invoking R under Mac OS X Scripting with R Next: Invoking R under Windows . Previous: Invoking R . These files should contain lines of the form ' name = value '. or reside in .. unless --no-init-file was given. and the section below for some Windows-specific details). otherwise. Most options control what happens at the beginning and at the end of an R session. if a function .First exists. if unset.googleusercontent.Rprofile in the current directory or in the user's home directory (in that order) is searched for. 84 de 99 25/02/2011 10:36 . The name of this file is taken from the value of the R_PROFILE environment variable.RData if there is one (unless --no-restore or --no-restore-data was specified). Unless --no-environ was given. (See help("Startup") for a precise description.

.RData in the directory where R was started) should be restored at startup or not. but can be set by the environment variable R_HISTFILE ) should be restored at startup or not. --no-environ Do not read any user file to set environment variables.Rhistory in the directory where R was started. -f file --file= file Take input from file : ' . but not together with -f or --file . packages. ( --encoding enc is also accepted. Implies --no-save unless --save has been set. See The command-line editor . --version Print version information to standard output and exit successfully. the user is asked for the desired behavior when ending the session with q() .googleusercontent. This option also affects tilde-expansion: see the help for path. This is useful when running R from within Emacs using the ESS (“Emacs Speaks Statistics”) package. --no-init-file and --no-restore . --no-site-file . Implies --no-save unless --save has been set. --no-init-file Do not read the user's profile at startup.Uma Introdução ao R http://translate. R installation puts everything (executables.000 bytes on the total length of expressions used in this way.) RHOME Print the path to the R “home directory” to standard output and exit successfully. (There is a limit of 10. etc. --save --no-save Control whether data sets should be saved or not at the end of the R session. -e expression Use expression as an input line.) --no-restore-history Control whether the history file (normally file . --vanilla Combine --no-save . --help -h Print short help message to standard output and exit successfully. --no-environ . ( --no-restore implies all the specific --no-restore-* options.) --no-readline (UNIX only) Turn off command-line editing via readline . --min-vsize= N --max-vsize= N 85 de 99 25/02/2011 10:36 . If neither is given in an interactive session. The default is to restore. --restore --no-restore --no-restore-data Control whether saved images (file . --encoding= enc Specify the encoding to be assumed for input from the console or stdin . Command-line editing is enabled by default interactive use (see --interactive ). this also includes --no-Rconsole . --no-Rconsole (Windows only) Prevent loading the Rconsole file at startup. Under Windows.com/translate_c?hl=pt-BR&ie=UTF-. Apart from the front-end shell script and the man page. --no-site-file Do not read the site-wide profile at startup.' means stdin .. in non-interactive use one of these must be specified or implied by some other option (see below). One or more -e options can be used. This needs to be an encoding known to iconv : see its help page.expand . The default is to restore.) into this directory. for more information.

--slave Make R run as quietly as possible.com/translate_c?hl=pt-BR&ie=UTF-. Warning and error messages are sent to the error channel ( stderr ).googleusercontent.. --interactive (UNIX only) Assert that R really is being run interactively even if input has been redirected: use if input is from a FIFO or pipe and fed from an interactive program. Currently the maximum value accepted is 100000. For most debuggers (the exceptions are valgrind and recent versions of gdb ). ' K '. It implies --quiet and --no-save . This is set by default to the smaller of 1. but the line length limit of 4095 bytes still applies. 86 de 99 25/02/2011 10:36 . This option is intended to support programs which use R to compute results for them.5Gb 24 and the amount of physical RAM in the machine. Currently. --min-nsize= N --max-nsize= N Specify the amount of memory used for fixed size objects by setting the number of “cons cells” to N .Uma Introdução ao R http://translate. N must either be an integer or an integer ending with ' G '. but can be increased to allow large and complicated calculations to be done. Note that input and output can be redirected in the usual way (using ' < ' and ' > '). (For back-compatibility. and must be between 32Mb and the maximum allowed on that version of Windows. This defaults to 10000. and should instead be given when starting the R executable from inside the debugger. ' Tk '. (The default is to deduce that R is being run interactively if and only if stdin is connected to a terminal or pty .) --args This flag does nothing except cause the rest of the command line to be skipped: this can be useful to retrieve values from it with commandArgs(TRUE) . provided that ' Tcl/Tk ' support is available. ' x11 ' and ' tk ' are accepted. possible values for type are ' X11 ' (the default) and. --debugger= name -d name (UNIX only) Run R through debugger name . -f or --file asserts non-interactive use even if --interactive is given. ' M '. --max-mem-size= N (Windows only) Specify a limit for the amount of memory to be used both for R objects and working areas. including asserting interactive use without the command-line editor. Here. and in particular set R's option verbose to TRUE . R code uses this option to control the printing of diagnostic messages. --verbose Print more information about progress.) Using -e . further command line options are disregarded. `Mega' (2^20). A cons cell takes 28 bytes on a 32-bit machine. --ess (Windows only) Set Rterm up for use by R-inferior-mode in ESS . meaning `Giga' (2^30). See the previous option for details on N . --gui= type -g type (UNIX only) Use type as graphical user interface (note that this also includes interactive graphics). and usually 56 bytes on a 64-bit machine. or ' k '. or regular `kilo' (1000). (computer) `Kilo' (2^10).. Specify the minimum or maximum amount of memory used for variable size objects by setting the “vector heap” size to N bytes. --max-ppsize= N Specify the maximum size of the pointer protection stack as N locations. --quiet --silent -q Do not print out the initial copyright and welcome messages.

Currently.com/translate_c?hl=pt-BR&ie=UTF-.. Rd2txt can be used as shorthand for Rd2conv -t txt . A forma geral é R CMD command args where command is the name of the tool and args the arguments passed on to it. package) add-on packages. and extracting the examples. plain text. INSTALL Install add-on packages. R.googleusercontent. and Rd files open (Windows only) Open a file via Windows' file associations texify (Windows only) Process (La)TeX files with R's style files Use R CMD command --help to obtain usage information for each of the tools accessible via the R CMD interface. LaTeX. but not intended to be called “directly”. Rprof Post-process R profiling files. 87 de 99 25/02/2011 10:36 . Rdconv Rd2txt Convert Rd format to various other formats. REMOVE Remove add-on packages. Stangle Extract S/R code from Sweave documentation Sweave Process Sweave documentation Rdiff Diff R output ignoring headers etc config Obtain configuration information javareconf (Unix only) Update the Java configuration variables rtags (Unix only) Create Emacs-style tag files from C. including HTML .Uma Introdução ao R http://translate. check Check add-on packages. LINK (UNIX only) Front-end for creating executable programs. build Build (that is. COMPILE (UNIX only) Compile files for use with R. The command R CMD allows the invocation of various tools which are useful in conjunction with R.. Rd2dvi Rd2pdf Convert Rd format to DVI/PDF. SHLIB Build shared library for dynamic loading. the following tools are available. BATCH Run R in batch mode. Rd2pdf can be used as shorthand for Rd2dvi --pdf .

invoking by R. (These are principally intended for batch use.com/translate_c?hl=pt-BR&ie=UTF-. Environment variables can be supplied as ' name = value ' pairs on the command line.exe . R tries to find system defined home directories. .googleusercontent. It will be run under the appropriate interpreter (Perl for . TMP and TEMP are either unset or one of them points to a valid place to create temporary files and directories.exe .2 Invoking R under Windows There are two ways to run R under Windows. (This mechanism is used for drag-and-drop and file association with RGui. For example. that gives the home directory.exe . Up: Invoking R B.) For interactive use.Uma Introdução ao R http://translate. including R_HOME . If the named file does not exist it sets the working directory if the parent directory exists. and trigger a break to the debugger during command line processing. Failing all those. --mdi --sdi --no-mdi Control whether Rgui will operate as an MDI program (with multiple child windows within one main window) or an SDI application (with multiple top-level windows for the console.exe . the methods described in the previous section may be used. BSTINPUTS and TEXINPUTS .exe . It first tries to use the Windows "personal" directory (typically C:\Documents and Settings\username\My Documents in Windows XP).Debug Enable the “Break to debugger” menu item in Rgui . and environment variables HOMEDRIVE and HOMEPATH are defined (and they normally are) these define the home directory. Next.sh or . The command-line setting overrides the setting in the user's Rconsole file. . as this is not always defined on Windows. If that fails. Under Windows with R CMD you may also specify your own . graphics and pager).) The following additional command-line options are available when invoking RGui..bat . PATH . that gives the home directory. the home directory is taken to be the starting directory.exe or more directly by Rterm.exe or a more capable shell). if 88 de 99 25/02/2011 10:36 .pl the appropriate interpreter (if available) is called to run it. . The startup procedure under Windows is very similar to that under UNIX. You need to ensure that either the environment variables TMPDIR . Next: Invoking R under Mac OS X .RData (in any case) it is interpreted as the path to the workspace to be restored: it implies --restore and sets the working directory to the parent of the named file. R_OSTYPE . but references to the `home directory' need to be clarified. if the environment variable HOME is defined. Under Windows cmd can be an executable or a batch file.pl file. you can use R CMD cmd args for any other executable cmd on the path: this is useful to have the same environment as R or the specific commands run under. there is a console-based GUI ( Rgui. but also works for Rterm. If the environment variable R_USER is defined.pl ) with several environment variables set appropriately. Within a terminal window (eg cmd. Previous: Invoking R from the command line . for example to run ldd or pdflatex .sh or . In addition. If there is an argument ending . After those two user-controllable settings. or if it has extension .exe )..

googleusercontent. It is a standard doubleclickable Mac OS X application.4 Scripting with R If you just want to run a file foo. If you want to run this in the background or as a batch job use OS-specific facilities to do so: for example in most shells on Unix-alike OSes R CMD BATCH foo.Uma Introdução ao R http://translate. Up: Invoking R B. This writes R output to stdout and stderr .R . Within a Terminal.tex . but R CMD texify mydoc will work in that case. with the path to R's share/texmf macros appended to TEXINPUTS .R arg1 arg2 and this can also be used to write executable script files like (at least on Unix-alikes. q(status=<exit status code>) If this is entered into a text file runfoo and this is made executable (by chmod 755 runfoo ). 89 de 99 25/02/2011 10:36 . The startup procedure under Mac OS X is very similar to that under UNIX. this does not help with the MiKTeX build of LaTeX.) Next: Scripting with R .app ) that by default is installed in the Applications folder on your system. which can be invoked by Rscript foo. you already have latex.com/translate_c?hl=pt-BR&ie=UTF-. the methods described in the first subsection apply. The `home directory' is the one inside the R. There is also console-based GUI ( R.exe on your path. Previous: Invoking R under Windows . Up: Invoking R B. then R CMD latex. (Unfortunately.R & runs a background job. and this can be redirected in the usual way for the shell running the command..R of R commands.3 Invoking R under Mac OS X There are two ways to run R under Mac OS X.app window by invoking R . it can be invoked for different arguments by runfoo arg1 arg2 For further options see help("Rscript") . You can pass parameters to scripts via additional arguments on the command line: for example R CMD BATCH --args arg1 arg2 foo. but the startup and current working directory are set as the user's home directory unless a different startup directory is given in the Preferences window accessible from within the GUI...exe mydoc will run LaTeX on mydoc.. and in some Windows shells) #! /path/to/Rscript args <.commandArgs(TRUE) This is made simpler by the alternative front-end Rscript .R & will pass arguments to a script which can be retrieved as a character vector by args <. Previous: Invoking R under Mac OS X .framework.commandArgs(TRUE) . the recommended way is to use R CMD BATCH foo.

.) . are obtained by holding the <CTRL> down while you press the <m> key. If you want to refer to the process's stdin .70 and stdin() refers to the script file to allow such traditional usage.70 2.scan(n=24) 2.googleusercontent.40 2.95 3. Up: Top Appendix C The command-line editor C. and written as Mb in the following. At least in Bourne and bash shells. One thing to consider is what stdin() refers to.03 3.50 2. an inbuilt command line editor allowing recall.20 3.70 2..03 28. you could type <ESC><b>. Very short scripts can be passed to Rscript on the command-line via the -e flag. EOF but here stdin() refers to the program source and "stdin" will not be usable.90 3. editing and re-submission of prior commands is used.exe . eg scan("stdin".40 3.40 2. the functions described below are available.10 3. If your terminal does not have a <META> key enabled. to enter Mb .Uma Introdução ao R http://translate.70 3.80 2.28 3. It is commonplace to write R scripts with segments like chem <. The ESC character sequences are also allowed on terminals 90 de 99 25/02/2011 10:36 .40 2. use "stdin" as a file connection. and the file README.60 3.70 3.. Control characters.50 3.com/translate_c?hl=pt-BR&ie=UTF-. Thus... Note that other versions of readline exist and may be used by the inbuilt command line editor: this used to happen on Mac OS X. are typed by holding down <META> 26 and pressing <b>.Rterm for command-line editing under Rterm. the #! mechanism does not allow extra arguments like #! /usr/bin/env Rscript --vanilla . When using R with readline capabilities.. It can be disabled (useful for usage with ESS 25 ) using the startup option --no-readline . use #! /usr/bin/env Rscript . If you do not wish to hardcode the path to Rscript but have it in your path (which is normally the case for an installed R except on Windows). Previous: Invoking R . Many of these use either Control or Meta characters.37 3.40 3.20 5. and are written as Cm below.. Another way to write executable script files (suggested by François Pinard) is to use a here document like #! / Bin / sh [environment variables can be set here] R --slave [other options] <<EOF R program goes here. you can still type Meta characters using two-character sequences starting with ESC . Next: Function and variable index .1 Preliminaries When the GNU readline library is available at the time R is configured for compilation under UNIX. such as Control-m . such as Meta-b . Meta characters.. .77 3. Windows versions of R have somewhat simpler command-line editing: see ' Console ' under the ' Help ' menu of the GUI .

Note that case is significant for Meta characters. Cr text Find the last command with the text string in it. Go forward one character. you can also use the up and down arrow keys instead of Cp and Cn .. C. Ce Go to the end of the line. Other editing actions are summarized in the following table. On most terminals. Mb Go back one word.googleusercontent. with real Meta keys. Horizontal motion of the cursor Ca Go to the beginning of the command.Uma Introdução ao R http://translate. Cb Go back one character. Pressing the <RET> command at any time causes the command to be re-submitted. respectively. and commands in your history may be recalled. respectively.3 Command-line editor summary Command recall and vertical motion Cp Go to the previous command (backwards in the history).com/translate_c?hl=pt-BR&ie=UTF-. Cf. <DEL> Cd Delete the character under the cursor. On most terminals. 91 de 99 25/02/2011 10:36 . In Emacs-style command-line editing any straight typing you do while in this editing phase causes the characters to be inserted in the command you are editing. Delete the previous character (left of the cursor). text Append text after the cursor. you can also use the left and right arrow keys instead of Cb and Cf .. changed if necessary. displacing any characters to the right of the cursor. Editing and re-submission texto Cf Insert text at the cursor. and re-submitted as new commands. In vi mode character insertion mode is started by Mi or Ma . Cn Go to the next command (forwards in the history). including the erroneous lines.2 Editing actions The R program keeps a history of the command lines you type. C. Mf Go forward one word. characters are typed and insertion mode is finished by typing a further <ESC>.

Ck Delete from cursor to end of command. The final <RET> terminates the command line editing sequence.First : Customizing the environment .: Scope <= : Logical vectors == : Logical vectors > : Logical vectors >= : Logical vectors ? : Getting help ?? : Getting help ^ : Vector arithmetic abline : Low-level plotting commands 92 de 99 25/02/2011 10:36 . Mc Change the rest of the word to upper case. Ct Transpose the character under the cursor with the next. <RET> Re-submit the command to R. Previous: The command-line editor . these customizations can be conditioned on application R . The readline key bindings can be customized in the usual way via a ~/. Ml Change the rest of the word to lower case.googleusercontent. and “save” it.inputrc file.Last : Customizing the environment / : Vector arithmetic : : Generating regular sequences :: : Namespaces ::: : Namespaces < : Logical vectors <<. Cy Insert (yank) the last “saved” text here.. and “save” it. Md Delete the rest of the word under the cursor. Up: Top Appendix D Function and variable index ! : Logical vectors != : Logical vectors %*% : Multiplication %o% : The outer product of two arrays & : Logical vectors && : Conditional execution * : Vector arithmetic + : Vector arithmetic .0.12. : Updating fitted models . As from R 2.: Vector arithmetic .com/translate_c?hl=pt-BR&ie=UTF-.Uma Introdução ao R http://translate.. that is by including a section like $if R "\C-xd": "q('no')\n" $endif Next: Concept index .

next : Multiple graphics devices dev.frame : Making data frames as.Uma Introdução ao R http://translate.data.list : Multiple graphics devices dev.vector : The concatenation function c() with arrays attach : attach() and detach() attr : Getting and setting attributes attributes : Getting and setting attributes avas : Some non-standard models axis : Low-level plotting commands boxplot : One.set : Multiple graphics devices deviance : Generic functions for extracting model information diag : Multiplication dim : Arrays dotchart : Display graphics drop1 : Updating fitted models ecdf : Examining the distribution of a set of data edit : Editing data eigen : Eigenvalues and eigenvectors else : Conditional execution Error : Analysis of variance and model comparison example : Getting help 93 de 99 25/02/2011 10:36 .frame : Making data frames density : Examining the distribution of a set of data det : Singular value decomposition and determinants detach : attach() and detach() determinant : Singular value decomposition and determinants dev..and two-sample tests break : Repetitive execution bruto : Some non-standard models C : Contrasts c : Concatenating lists c : The concatenation function c() with arrays c : Character vectors c : Vectors and assignment cbind : Forming partitioned matrices coef : Generic functions for extracting model information coefficients : Generic functions for extracting model information contour : Display graphics contrasts : Contrasts coplot : Displaying multivariate data cos : Vector arithmetic crossprod : Multiplication crossprod : Index matrices cut : Frequency tables from factors data : Accessing builtin datasets data.googleusercontent.prev : Multiple graphics devices dev.off : Multiple graphics devices dev.. ace : Some non-standard models add1 : Updating fitted models anova : ANOVA tables anova : Generic functions for extracting model information aov : Analysis of variance and model comparison aperm : Generalized transpose of an array array : The array() function as.com/translate_c?hl=pt-BR&ie=UTF-.

Uma Introdução ao R http://translate..na : Missing values is.search : Getting help help.nan : Missing values jpeg : Device drivers ks.googleusercontent.start : Getting help hist : Display graphics hist : Examining the distribution of a set of data identify : Interacting with graphics if : Conditional execution ifelse : Conditional execution image : Display graphics is. exp : Vector arithmetic F : Logical vectors factor : Factors FALSE : Logical vectors fivenum : Examining the distribution of a set of data for : Repetitive execution formula : Generic functions for extracting model information function : Writing your own functions getAnywhere : Object orientation getS3method : Object orientation glm : The glm() function help : Getting help help..test : Examining the distribution of a set of data legend : Low-level plotting commands length : The intrinsic attributes mode and length length : Vector arithmetic levels : Factors lines : Low-level plotting commands list : Lists lm : Linear models lme : Some non-standard models locator : Interacting with graphics loess : Some non-standard models log : Vector arithmetic lqs : Some non-standard models lsfit : Least squares fitting and the QR decomposition mars : Some non-standard models max : Vector arithmetic mean : Vector arithmetic methods : Object orientation min : Vector arithmetic mode : The intrinsic attributes mode and length NA : Missing values NaN : Missing values ncol : Matrix facilities next : Repetitive execution nlm : Maximum likelihood nlm : Least squares nlm : Nonlinear least squares and maximum likelihood models nlme : Some non-standard models nlminb : Nonlinear least squares and maximum likelihood models nrow : Matrix facilities optim : Nonlinear least squares and maximum likelihood models 94 de 99 25/02/2011 10:36 .com/translate_c?hl=pt-BR&ie=UTF-.

..Uma Introdução ao R http://translate.googleusercontent. order : Vector arithmetic ordered : Ordered factors outer : The outer product of two arrays pairs : Displaying multivariate data par : The par() function paste : Character vectors pdf : Device drivers persp : Display graphics plot : The plot() function plot : Generic functions for extracting model information pmax : Vector arithmetic pmin : Vector arithmetic png : Device drivers points : Low-level plotting commands polygon : Low-level plotting commands postscript : Device drivers predict : Generic functions for extracting model information print : Generic functions for extracting model information prod : Vector arithmetic qqline : Display graphics qqline : Examining the distribution of a set of data qqnorm : Display graphics qqnorm : Examining the distribution of a set of data qqplot : Display graphics qr : Least squares fitting and the QR decomposition quartz : Device drivers range : Vector arithmetic rbind : Forming partitioned matrices read.table() function rep : Generating regular sequences repeat : Repetitive execution resid : Generic functions for extracting model information residuals : Generic functions for extracting model information rlm : Some non-standard models rm : Data permanency and removing objects scan : The scan() function sd : The function tapply() and ragged arrays search : Managing the search path seq : Generating regular sequences shapiro.test : Examining the distribution of a set of data sin : Vector arithmetic sink : Executing commands from or diverting output to a file solve : Linear equations and inversion sort : Vector arithmetic source : Executing commands from or diverting output to a file split : Repetitive execution sqrt : Vector arithmetic stem : Examining the distribution of a set of data step : Updating fitted models step : Generic functions for extracting model information sum : Vector arithmetic summary : Generic functions for extracting model information summary : Examining the distribution of a set of data svd : Singular value decomposition and determinants 95 de 99 25/02/2011 10:36 .com/translate_c?hl=pt-BR&ie=UTF-.table : The read.

t : Generalized transpose of an array T : Logical vectors t.and two-sample tests table : Frequency tables from factors table : Index matrices tan : Vector arithmetic tapply : The function tapply() and ragged arrays text : Low-level plotting commands title : Low-level plotting commands tree : Some non-standard models TRUE : Logical vectors unclass : The class of an object update : Updating fitted models var : The function tapply() and ragged arrays var : Vector arithmetic var..com/translate_c?hl=pt-BR&ie=UTF-.and two-sample tests windows : Device drivers X11 : Device drivers | : Logical vectors || : Conditional execution ~ : Formulae for statistical models Next: References .and two-sample tests vcov : Generic functions for extracting model information vector : Vectors and assignment while : Repetitive execution wilcox.test : One. Up: Top Appendix E Concept index Accessing builtin datasets : Accessing builtin datasets Additive models : Some non-standard models Analysis of variance : Analysis of variance and model comparison Arithmetic functions and operators : Vector arithmetic Arrays : Arrays Assignment : Vectors and assignment Attributes : Objects Binary operators : Defining new binary operators Box plots : One.Uma Introdução ao R http://translate.test : One. Previous: Function and variable index ..googleusercontent.and two-sample tests Character vectors : Character vectors Classes : Object orientation Classes : The class of an object Concatenating lists : Concatenating lists Contrasts : Contrasts Control statements : Control statements CRAN : Contributed packages and CRAN Customizing the environment : Customizing the environment Data frames : Data frames Default values : Named arguments and defaults Density estimation : Examining the distribution of a set of data Determinants : Singular value decomposition and determinants Diverting input and output : Executing commands from or diverting output to a file Dynamic graphics : Dynamic graphics Eigenvalues and eigenvectors : Eigenvalues and eigenvectors 96 de 99 25/02/2011 10:36 .test : One.

and two-sample tests : One.and two-sample tests Tabulation : Frequency tables from factors Tree-based models : Some non-standard models Updating fitted models : Updating fitted models 97 de 99 25/02/2011 10:36 .com/translate_c?hl=pt-BR&ie=UTF-.and two-sample tests Ordered factors : Contrasts Ordered factors : Factors Outer products of arrays : The outer product of two arrays Packages : Packages Packages : R and statistics Probability distributions : Probability distributions QR decomposition : Least squares fitting and the QR decomposition Quantile-quantile plots : Examining the distribution of a set of data Reading data from files : Reading data from files Recycling rule : The recycling rule Recycling rule : Vector arithmetic Regular sequences : Generating regular sequences Removing objects : Data permanency and removing objects Robust regression : Some non-standard models Scope : Scope Search path : Managing the search path Shapiro-Wilk test : Examining the distribution of a set of data Singular value decomposition : Singular value decomposition and determinants Statistical models : Statistical models in R Student's t test : One..googleusercontent.. Empirical CDFs : Examining the distribution of a set of data Factors : Contrasts Factors : Factors Families : Families Formulae : Formulae for statistical models Generalized linear models : Generalized linear models Generalized transpose of an array : Generalized transpose of an array Generic functions : Object orientation Graphics device drivers : Device drivers Graphics parameters : The par() function Grouped expressions : Grouped expressions Indexing of and by arrays : Array indexing Indexing vectors : Index vectors Kolmogorov-Smirnov test : Examining the distribution of a set of data Least squares fitting : Least squares fitting and the QR decomposition Linear equations : Linear equations and inversion Linear models : Linear models Lists : Lists Local approximating regressions : Some non-standard models Loops and conditional execution : Loops and conditional execution Matrices : Arrays Matrix multiplication : Multiplication Maximum likelihood : Maximum likelihood Missing values : Missing values Mixed models : Some non-standard models Named arguments : Named arguments and defaults Namespace : Namespaces Nonlinear least squares : Nonlinear least squares and maximum likelihood models Object orientation : Object orientation Objects : Objects One.Uma Introdução ao R http://translate.

. [ 8 ] paste(. Vectors : Simple manipulations numbers and vectors Wilcoxon test : One.and two-sample tests Workspace : Data permanency and removing objects Writing functions : Writing your own functions Previous: Concept index . Annette J.Last. Hastie eds. the action of c() is rather different. Peter McCullagh and John A. [4] [5] [6] of unlimited length. see the help for sub and substring . Statistical Models in S. Second edition. Nelder (1989). Duxbury Press. Richard A. Chapman and Hall. SD Silvey (1970).com/translate_c?hl=pt-BR&ie=UTF-. This book is often called the “ Blue Book ”.googleusercontent. Second edition. it is still available as . Nonlinear Regression Analysis and Its Applications. de Nova York. Chambers and Trevor J. collapse= ss ) joins the arguments into a single character string putting ss in between. London. and amongst those which do some will silently discard the excess and some will use it as the start of the next line. London. Cambridge University Press. Chapman and Hall. Chambers (1998) Programming with Data . Generalized Linear Models. Chambers and Allan R.value before any other statements are executed. Mathematical Statistics and Data Analysis. There are more tools for character manipulation. [7] Actually. Statistical Inference.. This is also called the “ Green Book ”. 25/02/2011 10:36 98 de 99 .. John Wiley & Sons. Springer. New York. such as list mode arguments. AC Davison and DV Hinkley (1997). [1] [2] [3] not inside strings. Bootstrap Methods and Their Applications . (1992). An Introduction to Generalized Linear Models . Belmont. Chapman & Hall. With other than vector types of argument.. Wilks (1988). Dobson (1990). John A. The leading “dot” in this file name makes it invisible in normal file listings in UNIX. John M. Rice (1995). London.Uma Introdução ao R http://translate. Chapman & Hall. Becker. The New S Language.. See Concatenating lists . John M. Notas de Rodapé For portable R code (including that to be used in R packages) only A–Za–z0–9 should be used. John M. CA. New York. nor within the argument list of a function definition some of the consoles will not allow you to enter more. Penguin. Up: Top Appendix F References DM Bates and DG Watts (1988). New York. This is also called the “ White Book ”.

com/translate_c?hl=pt-BR&ie=UTF-. occasionally the `Windows' key. The `Emacs Speaks Statistics' package. because of roundoff errors in the character representation. eg.Uma Introdução ao R http://translate. Victoria and Western Australia. the best way to compute x'x or xx' is crossprod(x) or x %o% x respectively. as explained in the manual. perhaps using the Cholesky or eigendecomposition of A. coercion from numeric to character and back again will not be exactly reversible.R-project. South Australia. namely the Australian Capital Territory. namely integer and double precision.. as it could mean either x'x or x x'.. Under UNIX. [ 10 ] [ 11 ] In general. Note however that length( object ) does not always contain intrinsic useful information. New South Wales. ' tapply(incomes. Queensland.9. [ 12 ] [ 13 ] Readers should note that there are eight states and territories in Australia. [ 23 ] [ 24 ] 2. A different style using `formal' or `S4' classes is provided in package methods . the utilities Sed or Awk can be used. [ 16 ] [ 17 ] [ 18 ] [ 19 ] [ 20 ] [ 21 ] See the on-line help for autoload for the meaning of the second term. the Northern Territory. eg. [ 14 ] Note that tapply() also works in this case when its second argument is not a factor. [9] numeric mode is actually an amalgam of two distinct modes. to be discussed later.googleusercontent.5Gb on versions of Windows that support 3Gb per process and have the support enabled: see the rw-FAQ Q2. where x is the column form. Even better would be to form a matrix square root B with A = BB' and find the squared length of the solution of By = x. The matrix xx' may be calculated either by cbind(x) %*% x or x %*% rbind(x) since the result of rbind() or cbind() is always a matrix. and this is true for quite a few other functions. See also the methods described in Statistical models in R In some sense this mimics the behavior in S-PLUS since in S-P LUS this operator always creates or assigns to a global variable.5Gb on some 64-bit versions of Windows. However.factor() ).org On a PC keyboard this is usually the Alt key. Tasmania. Some graphics parameters such as the size of the current device are for information only. state) '. [ 22 ] So it is hidden under UNIX. [ 15 ] Note that x %*% x is ambiguous. [ 25 ] [ 26 ] 99 de 99 25/02/2011 10:36 . or use xyplot from package lattice . 3. since arguments are coerced to factors when necessary (using as. see the URL http://ESS. when object is a function. In such cases the smaller matrix seems implicitly to be the interpretation adopted. so the scalar x'x is in this case the result.