# data[].attributes.headline
Achei algumas explicações e comandos úteis

# data[].attributes.subject
Achei algumas explicações e comandos úteis

# data[].attributes.attachment_link.readable_text
Campo em crescimento exponencial, Ciência de Dados tem se tornado uma área apaixonante para entusiastas das mais diversas áreas. Estatísticos contribuem com sólida teoria de análise de dados enquanto cientistas e engenheiros da computação contribuem com novas capacidades e possibilidades computacionais. Assim, pesquisadores(as) da biologia, psicologia, direito, economia, comunicação, sociologia e diversas outras áreas podem usufruir desse conjunto de técnicas (algumas nem tão novas) para aprimorar e desenvolver suas pesquisas. E a linguagem R é uma das principais linguagens de programação utilizadas para isso.

O seu caráter aberto e a construção pela comunidade científica fez com que o R ultrapassasse a marca de dez mil pacotes, conjunto de códigos com funções específicas que facilitam a vida de todo mundo. Todos gratuitos.

Mas mais importante de tudo isso, é um recado simples e direto: R é para você também. Este livro (ebook em bookdown) consolida o que nossos professores vieram ensinando em nosso curso introdutório de R nos últimos anos. Foi construído com a nossa experiência didática em dezenas de turmas em todo o Brasil com bons exemplos e será constantemente melhorado com a opinião e sugestões dos nossos alunos.

Espero que a leitura e principalmente a prática sejam proveitosas.

Boa jornada.

Max Stabile CEO - IBPAD

# data[].attributes.attachment_link.authors[].name
Saulo Guerra, Paulo Felipe de Oliveira, Robert McDonnell e Sillas Gonzaga

# data[].attributes.attachment_link.description
Campo em crescimento exponencial, Ciência de Dados tem se tornado uma área apaixonante para entusiastas das mais diversas áreas. Estatísticos contribuem com sólida teoria de análise de dados enquanto cientistas e engenheiros da computação contribuem com novas capacidades e possibilidades computacionais.

# data[].attributes.headline
Achei bem clara essa explicação de interpretação de interação para análise de lmer com 2 ou mais variáveis:

# data[].attributes.subject
Achei bem clara essa explicação de interpretação de interação para análise de lmer com 2 ou mais variáveis:

# data[].attributes.attachment_link.readable_text
$\begingroup$

I have a problem with interpreting 2-way and 3-way interactions in lmer. My DV is height which is a continuous variable. All IVs are categorical variables. The first factor is animal, either rat or lion. The second factor is sex, either male or female. The third factor is color: red, white, or yellow. I get confused with interpreting the output:

Fixed effects: Estimate Std. Error t value (Intercept) 164.6888 7.8180 21.065 rat -14.1342 8.2889 -1.705 sexmale -16.0883 10.0071 -1.608 colorred 0.5776 6.2473 0.092 coloryellow -14.4048 6.1025 -2.360 rat:sexmale 15.3645 11.8567 1.296 rat:colorred 12.5258 4.4028 2.845 rat:coloryellow 10.3136 4.3196 2.388 sexmale:colorred 2.0272 5.2773 0.384 sexmale:coloryellow 5.7643 5.1669 1.116 rat:sexmale:colorred -5.5144 6.2838 -0.878 rat:sexmale:coloryellow 0.9735 6.1690 2.158

According to Vasishth et al. (2007), the significance of fixed effects can be judged from the absolute t value; if it is higher than 2, then that factor is significant. In interpreting this output, I choose only factors which are significant. Please check if my interpretations are correct:

1. coloryellow = The height of subjects are lower when they like yellow, and are higher if they like white.

2. rat:colorred = The effect of rat preference enhances the preference of red, and these two promote height of subjects.

3. rat:sexmale:coloryellow = The effect of rat preference, being male, enhances the preference of yellow, and subjects who like rat and yellow and are male have higher height.

From these interpretations, I would like to ask: if I would like to know the effect of lion:sexfemale:colorred, and rat:sexmale:colorred compared to rat:sexfemale:coloorred, do I have to run new statistics?

# data[].attributes.attachment_link.title
How to interpret 2-way and 3-way interaction in lmer?

# data[].attributes.attachment_link.description
begingroup$ I have a problem with interpreting 2-way and 3-way interactions in lmer. My DV is height which is a continuous variable. All IVs are categorical variables. The first factor is animal, either rat or lion. The second factor is sex, either male or female. The third factor is color: red, white, or yellow.

# data[].attributes.headline
Comunidade/fórum para procurar respostas sobre dúvidas

# data[].attributes.subject
Comunidade/fórum para procurar respostas sobre dúvidas

# data[].attributes.attachment_link.readable_text
Want a secure, private space for your technical knowledge?

Discover Teams

monthly visitors to Stack Overflow & Stack Exchange

Times a developer got help since 2008

from companies using Stack Overflow for Teams

Stack Overflow for Teams instances active every day

A public platform building the definitive collection of coding questions & answers

A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.

Join the community

or search content

A private collaboration & knowledge sharing SaaS platform for companies

A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.

Robust read and write API

Single sign-on with AD or SAML

Your own customer success representative

99.5% uptime SLA and priority support

About the company
Want to work here? Current job openings

Create a free Team

# data[].attributes.attachment_link.title
Stack Overflow - Where Developers Learn, Share, & Build Careers

# data[].attributes.attachment_link.description
Stack Overflow is the largest, most trusted online community for developers to learn, share​ ​their programming ​knowledge, and build their careers.

# data[].attributes.headline
Site com explicações rápidas e simples sobre R para iniciantes

# data[].attributes.subject
Site com explicações rápidas e simples sobre R para iniciantes

# data[].attributes.attachment_link.readable_text
Obtaining R

R is available for Linux, MacOS, and Windows. Software can be downloaded from The Comprehensive R Archive Network (CRAN).

Startup

After R is downloaded and installed, simply find and launch R from your Applications folder.

Entering Commands

R is a command line driven program. The user enters commands at the prompt (> by default) and each command is executed one at a time.

The workspace is your current R working environment and includes any user-defined objects (vectors, matrices, data frames, lists, functions). At the end of an R session, the user can save an image of the current workspace that is automatically reloaded the next time R is started.

Graphic User Interfaces

Aside from the built in R console, RStudio is the most popular R code editor, and it interfaces with R for Windows, MacOS, and Linux platforms.

R's binary and logical operators will look very familiar to programmers. Note that binary operators work on vectors and matrices as well as scalars.

Arithmetic Operators include:

Logical Operators include:

R has a wide variety of data types including scalars, vectors (numerical, character, logical), matrices, data frames, and lists.

Use the assignment operator <- to create new variables.
# An example of computing the mean with variables

mydata$sum <- mydata$x1 + mydata$x2
mydata$mean <- (mydata$x1 + mydata$x2)/2

Almost everything in R is done through functions. A function is a piece of code written to carry out a specified task; it may accept arguments or parameters (or not) and it may return one or more values (or not!). In R, a function is defined with the construct:

The code in between the curly braces is the body of the function. Note that by using built-in functions, the only thing you need to worry about is how to effectively communicate the correct input arguments (arglist) and manage the return value/s (if any).

Importing data into R is fairly simple. R offers options to import many file types, from CSVs to databases.

For example, this is how to import a CSV into R.
# first row contains variable names, comma is separator
# assign the variableid to row names
# note the / instead of \ on mswindows systems

mydata <- read.table("c:/mydata.csv", header=TRUE,
sep=",", row.names="id")
R provides a wide range of functions for obtaining summary statistics. One way to get descriptive statistics is to use the sapply( ) function with a specified summary statistic.

Below is how to get the mean with the sapply( ) function:
# get means for variables in data frame mydata
# excluding missing values
sapply(mydata, mean, na.rm=TRUE)
Possible functions used in sapply include mean, sd, var, min, max, median, range, and quantile.

In R, graphs are typically created interactively. Here is an example:
# Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")
The plot( ) function opens a graph window and plots weight vs. miles per gallon. The next line of code adds a regression line to this graph. The final line adds a title.

Packages

Packages are collections of R functions, data, and compiled code in a well-defined format. The directory where packages are stored is called the library. R comes with a standard set of packages. Others are available for download and installation. Once installed, they have to be loaded into the session to be used.
.libPaths() # get library location
library() # see all packages installed
search() # see packages currently loaded
Once R is installed, there is a comprehensive built-in help system. At the program's command prompt you can use any of the following:
help.start() # general help
help(foo) # help about function foo
?foo # same thing
apropos("foo") # list all functions containing string foo
example(foo) # show an example of function foo
Going Further

If you prefer an online interactive environment to learn R, this free R tutorial by DataCamp is a great way to get started.

# data[].attributes.attachment_link.description
R is available for Linux, MacOS, and Windows. Software can be downloaded from The Comprehensive R Archive Network (CRAN). After R is downloaded and installed, simply find and launch R from your Applications folder. R is a command line driven program.

# data[].attributes.body
Achei muito interessante, gente. https://instagram.com/estatisticaaplicada?utm_medium=copy_link

# data[].attributes.headline
Link para o minicurso Análise Colostrucional Através do R (Divulgado pela Marije no Classroom)

# data[].attributes.subject
Link para o minicurso Análise Colostrucional Através do R (Divulgado pela Marije no Classroom)

# data[].attributes.body
https://www.youtube.com/watch?v=-lh215zX36U&list=PLs_n0oj-a3rkMbFMmy5duPu4LzrzNRh2b&index=6

# data[].attributes.headline
Esta página é bem útil para estatística descritiva simples:

# data[].attributes.subject
Esta página é bem útil para estatística descritiva simples:

# data[].attributes.attachment_link.readable_text
Descriptive statistics consist of describing simply the data using some summary statistics and graphics. Here, we'll describe how to compute summary statistics using R software.

1. Prepare your data as specified here: Best practices for preparing your data set for R

2. Save your data in an external .txt tab or .csv files

3. Import your data into R as follow:

# If .txt tab file, use this my_data

Here, we'll use the built-in R data set named iris.

# Store the data in the variable my_data my_data

You can inspect your data using the functions head() and tails(), which will display the first and the last part of the data, respectively.

# Print the first 6 rows head(my_data, 6)

 Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa

Some R functions for computing descriptive statistics:

The function mfv(), for most frequent value, [in modeest package] can be used to find the statistical mode of a numeric vector.

Measure of variablity

Measures of variability gives how "spread out" the data are.

Range: minimum & maximum

Range corresponds to biggest value minus the smallest value. It gives you the full spread of the data.

# Compute the minimum value min(my_data$Sepal.Length)

[1] 4.3

# Compute the maximum value max(my_data$Sepal.Length)

[1] 7.9

# Range range(my_data$Sepal.Length)

[1] 4.3 7.9

Interquartile range

Recall that, quartiles divide the data into 4 parts. Note that, the interquartile range (IQR) - corresponding to the difference between the first and third quartiles - is sometimes used as a robust alternative to the standard deviation.

quantile(x, probs = seq(0, 1, 0.25))

x: numeric vector whose sample quantiles are wanted.

probs: numeric vector of probabilities with values in [0,1].

quantile(my_data$Sepal.Length)

 0% 25% 50% 75% 100% 4.3 5.1 5.8 6.4 7.9

By default, the function returns the minimum, the maximum and three quartiles (the 0.25, 0.50 and 0.75 quartiles).

To compute deciles (0.1, 0.2, 0.3, ...., 0.9), use this:

quantile(my_data$Sepal.Length, seq(0, 1, 0.1))

To compute the interquartile range, type this:

IQR(my_data$Sepal.Length)

[1] 1.3

Variance and standard deviation

The variance represents the average squared deviation from the mean. The standard deviation is the square root of the variance. It measures the average deviation of the values, in the data, from the mean value.

# Compute the variance var(my_data$Sepal.Length) # Compute the standard deviation = # square root of th variance sd(my_data$Sepal.Length)

Which measure to use?

Range. It's not often used because it's very sensitive to outliers.

Interquartile range. It's pretty robust to outliers. It's used a lot in combination with the median.

Variance. It's completely uninterpretable because it doesn't use the same units as the data. It's almost never used except as a mathematical tool

Standard deviation. This is the square root of the variance. It's expressed in the same units as the data. The standard deviation is often used in the situation where the mean is the measure of central tendency.

Median absolute deviation. It's a robust way to estimate the standard deviation, for data with outliers. It's not used very often.

In summary, the IQR and the standard deviation are the two most common measures used to report the variability of the data.

Computing an overall summary of a variable and an entire data frame

summary() function

The function summary() can be used to display several statistic summaries of either one variable or an entire data frame.

Summary of a single variable. Five values are returned: the mean, median, 25th and 75th quartiles, min and max in one single line call:

summary(my_data$Sepal.Length)

 Min. 1st Qu. Median Mean 3rd Qu. Max. 4.300 5.100 5.800 5.843 6.400 7.900

Summary of a data frame. In this case, the function summary() is automatically applied to each column. The format of the result depends on the type of the data contained in the column. For example:

If the column is a numeric variable, mean, median, min, max and quartiles are returned.

If the column is a factor variable, the number of observations in each group is returned.

summary(my_data, digits = 1)

 Sepal.Length Sepal.Width Petal.Length Petal.Width Species Min. :4 Min. :2 Min. :1 Min. :0.1 setosa :50 1st Qu.:5 1st Qu.:3 1st Qu.:2 1st Qu.:0.3 versicolor:50 Median :6 Median :3 Median :4 Median :1.3 virginica :50 Mean :6 Mean :3 Mean :4 Mean :1.2 3rd Qu.:6 3rd Qu.:3 3rd Qu.:5 3rd Qu.:1.8 Max. :8 Max. :4 Max. :7 Max. :2.5

sapply() function

It's also possible to use the function sapply() to apply a particular function over a list or vector. For instance, we can use it, to compute for each column in a data frame, the mean, sd, var, min, quantile, ...

# Compute the mean of each column sapply(my_data[, -5], mean)

Sepal.Length Sepal.Width Petal.Length Petal.Width 5.843333 3.057333 3.758000 1.199333

# Compute quartiles sapply(my_data[, -5], quantile)

 Sepal.Length Sepal.Width Petal.Length Petal.Width 0% 4.3 2.0 1.00 0.1 25% 5.1 2.8 1.60 0.3 50% 5.8 3.0 4.35 1.3 75% 6.4 3.3 5.10 1.8 100% 7.9 4.4 6.90 2.5

stat.desc() function

The function stat.desc() [in pastecs package], provides other useful statistics including:

install.packages("pastecs")

Use the function stat.desc() to compute descriptive statistics

# Compute descriptive statistics library(pastecs) res

 Sepal.Length Sepal.Width Petal.Length Petal.Width nbr.val 150.00 150.00 150.00 150.00 nbr.null 0.00 0.00 0.00 0.00 nbr.na 0.00 0.00 0.00 0.00 min 4.30 2.00 1.00 0.10 max 7.90 4.40 6.90 2.50 range 3.60 2.40 5.90 2.40 sum 876.50 458.60 563.70 179.90 median 5.80 3.00 4.35 1.30 mean 5.84 3.06 3.76 1.20 SE.mean 0.07 0.04 0.14 0.06 CI.mean.0.95 0.13 0.07 0.28 0.12 var 0.69 0.19 3.12 0.58 std.dev 0.83 0.44 1.77 0.76 coef.var 0.14 0.14 0.47 0.64

Case of missing values

Note that, when the data contains missing values, some R functions will return errors or NA even if just a single value is missing.

For example, the mean() function will return NA if even only one value is missing in a vector. This can be avoided using the argument na.rm = TRUE, which tells to the function to remove any NAs before calculations. An example using the mean function is as follow:

mean(my_data$Sepal.Length, na.rm = TRUE)

Graphical display of distributions

The R package ggpubr will be used to create graphs.

Installation and loading ggpubr

Install the latest version from GitHub as follow:

# Install if(!require(devtools)) install.packages("devtools") devtools::install_github("kassambara/ggpubr")

Or, install from CRAN as follow:

install.packages("ggpubr")

library(ggpubr)

Box plots

ggboxplot(my_data, y = "Sepal.Length", width = 0.5)

Histogram

Histograms show the number of observations that fall within specified divisions (i.e., bins).

Histogram plot of Sepal.Length with mean line (dashed line).

gghistogram(my_data, x = "Sepal.Length", bins = 9, add = "mean")

Empirical cumulative distribution function (ECDF)

ECDF is the fraction of data smaller than or equal to x.

ggecdf(my_data, x = "Sepal.Length")

Q-Q plots

QQ plots is used to check whether the data is normally distributed.

ggqqplot(my_data, x = "Sepal.Length")

To compute summary statistics by groups, the functions group_by() and summarise() [in dplyr package] can be used.

We want to group the data by Species and then:

compute the number of element in each group. R function: n()

compute the mean. R function mean()

and the standard deviation. R function sd()

The function %>% is used to chaine operations.

Install ddplyr as follow:

install.packages("dplyr")

Descriptive statistics by groups:

library(dplyr) group_by(my_data, Species) %>% summarise( count = n(), mean = mean(Sepal.Length, na.rm = TRUE), sd = sd(Sepal.Length, na.rm = TRUE) )

Source: local data frame [3 x 4] Species count mean sd (fctr) (int) (dbl) (dbl) 1 setosa 50 5.006 0.3524897 2 versicolor 50 5.936 0.5161711 3 virginica 50 6.588 0.6358796

Graphics for grouped data:

library("ggpubr") # Box plot colored by groups: Species ggboxplot(my_data, x = "Species", y = "Sepal.Length", color = "Species", palette = c("#00AFBB", "#E7B800", "#FC4E07"))

# Stripchart colored by groups: Species ggstripchart(my_data, x = "Species", y = "Sepal.Length", color = "Species", palette = c("#00AFBB", "#E7B800", "#FC4E07"), add = "mean_sd")

Note that, when the number of observations per groups is small, it's recommended to use strip chart compared to box plots.

A frequency table (or contingency table) is used to describe categorical variables. It contains the counts at each combination of factor levels.

R function to generate tables: table()

Create some data

Distribution of hair and eye color by sex of 592 students:

# Hair/eye color data df

 Hair Eye Sex 1 Black Brown Male 2 Black Brown Male 3 Black Brown Male 4 Black Brown Male 5 Black Brown Male 6 Black Brown Male

# hair/eye variables Hair

Simple frequency distribution: one categorical variable

# Frequency distribution of hair color table(Hair)

Hair Black Brown Red Blond 108 286 71 127

# Frequency distribution of eye color table(Eye)

Eye Brown Blue Hazel Green 220 215 93 64

Graphics: to create the graphics, we start by converting the table as a data frame.

# Compute table and convert as data frame df

 Hair Freq 1 Black 108 2 Brown 286 3 Red 71 4 Blond 127

# Visualize using bar plot library(ggpubr) ggbarplot(df, x = "Hair", y = "Freq")

Two-way contingency table: Two categorical variables

tbl2

 Eye Hair Brown Blue Hazel Green Black 68 20 15 5 Brown 119 84 54 29 Red 26 17 14 14 Blond 7 94 10 16

It's also possible to use the function xtabs(), which will create cross tabulation of data frames with a formula interface.

xtabs(~ Hair + Eye, data = hair_eye_col)

Graphics: to create the graphics, we start by converting the table as a data frame.

df

 Hair Eye Freq 1 Black Brown 68 2 Brown Brown 119 3 Red Brown 26 4 Blond Brown 7 5 Black Blue 20 6 Brown Blue 84

# Visualize using bar plot library(ggpubr) ggbarplot(df, x = "Hair", y = "Freq", color = "Eye", palette = c("brown", "blue", "gold", "green"))

# position dodge ggbarplot(df, x = "Hair", y = "Freq", color = "Eye", position = position_dodge(), palette = c("brown", "blue", "gold", "green"))

Multiway tables: More than two categorical variables

Hair and Eye color distributions by sex using xtabs():

xtabs(~Hair + Eye + Sex, data = hair_eye_col)

, , Sex = Male Eye Hair Brown Blue Hazel Green Black 32 11 10 3 Brown 53 50 25 15 Red 10 10 7 7 Blond 3 30 5 8 , , Sex = Female Eye Hair Brown Blue Hazel Green Black 36 9 5 2 Brown 66 34 29 14 Red 16 7 7 7 Blond 4 64 5 8

You can also use the function ftable() [for flat contingency tables]. It returns a nice output compared to xtabs() when you have more than two variables:

ftable(Sex + Hair ~ Eye, data = hair_eye_col)

 Sex Male Female Hair Black Brown Red Blond Black Brown Red Blond Eye Brown 32 53 10 3 36 66 16 4 Blue 11 50 10 30 9 34 7 64 Hazel 10 25 7 5 5 29 7 5 Green 3 15 7 8 2 14 7 8

Compute table margins and relative frequency

Table margins correspond to the sums of counts along rows or columns of the table. Relative frequencies express table entries as proportions of table margins (i.e., row or column totals).

The function margin.table() and prop.table() can be used to compute table margins and relative frequencies, respectively.

Format of the functions:

margin.table(x, margin = NULL) prop.table(x, margin = NULL)

x: table

margin: index number (1 for rows and 2 for columns)

compute table margins:

Hair

 Eye Hair Brown Blue Hazel Green Black 68 20 15 5 Brown 119 84 54 29 Red 26 17 14 14 Blond 7 94 10 16

# Margin of rows margin.table(he.tbl, 1)

Hair Black Brown Red Blond 108 286 71 127

# Margin of columns margin.table(he.tbl, 2)

Eye Brown Blue Hazel Green 220 215 93 64

Compute relative frequencies:

# Frequencies relative to row total prop.table(he.tbl, 1)

 Eye Hair Brown Blue Hazel Green Black 0.62962963 0.18518519 0.13888889 0.04629630 Brown 0.41608392 0.29370629 0.18881119 0.10139860 Red 0.36619718 0.23943662 0.19718310 0.19718310 Blond 0.05511811 0.74015748 0.07874016 0.12598425

# Table of percentages round(prop.table(he.tbl, 1), 2)*100

 Eye Hair Brown Blue Hazel Green Black 63 19 14 5 Brown 42 29 19 10 Red 37 24 20 20 Blond 6 74 8 13

To express the frequencies relative to the grand total, use this:

he.tbl/sum(he.tbl)

This analysis has been performed using R software (ver. 3.2.4).

Recommended for you

This section contains best data science and self-development resources to help you on your path.

Coursera - Online Courses and Specialization

Data science

Popular Courses Launched in 2020

Trending Courses

Books - Data Science

Our Books

Others

Want to Learn More on R Programming and Data Science?

Follow us by Email On Social Networks:

Get involved :
Click to follow us on Facebook and Google+ :
Comment this article by clicking on "Discussion" button (top-right position of this page)

# data[].attributes.attachment_link.description
Descriptive statistics consist of describing simply the data using some summary statistics and graphics. Here, we'll describe how to compute summary statistics using R software.

# data[].attributes.headline
Estatística com R para linguística: uma introdução prática, Gries. Tradução de Mello et al (2019).

# data[].attributes.subject
Estatística com R para linguística: uma introdução prática, Gries. Tradução de Mello et al (2019).

# data[].attributes.headline
Para quem quiser entender um pouquinho mais de Análise de Variância e estatística F

# data[].attributes.subject
Para quem quiser entender um pouquinho mais de Análise de Variância e estatística F

# data[].attributes.attachment_link.readable_text
*Alguns dos links relacionados podem conter informações em outros idiomas

A análise de variância (ANOVA) pode determinar se as médias de três ou mais grupos são diferentes. A ANOVA usa testes F para testar estatisticamente a igualdade entre médias. Neste post, mostrarei como a ANOVA e os testes F funcionam, usando um exemplo de ANOVA com um fator.

Mas espere um minuto... você já parou para pensar por que você usaria uma análise de variância para determinar se as médias são diferentes? Também mostrarei como as variâncias fornecem informações sobre as médias.

Como em meus posts sobre o entendimento de testes-t, vou me concentrar em conceitos e gráficos ao invés de equações para explicar os testes F de ANOVA.

O que são as estatísticas F e o teste F?

Os testes-F recebem seu nome da sua estatística de teste, F, que recebeu seu nome em homenagem a Sir Ronald Fisher. A estatística F é simplesmente uma razão de duas variâncias. As variâncias são uma medida de dispersão, ou até que ponto os dados estão dispersos em relação à sua média. Valores maiores representam maior dispersão.

A variância é o quadrado do desvio padrão. Para nós humanos, os desvios padrão são mais fáceis de entender do que as variâncias pois estão nas mesmas unidades que os dados, e não nas unidades quadradas. No entanto, muitas análises realmente usam variâncias em seus cálculos.

As estatísticas F são baseadas na razão de quadrados médios. O termo quadrados médios pode soar confuso, mas é simplesmente uma estimativa da variância populacional que explica os graus de liberdade (DF) usados para calcular essa estimativa.

Apesar de ser uma razão entre variâncias, você pode usar os testes F em uma várias situações. Obviamente o teste F pode avaliar a igualdade entre variâncias. No entanto, alterando as variâncias incluídas na razão, o teste F torna-se um teste muito flexível. Por exemplo, você pode usar estatísticas F e testes F para testar a significância global de um modelo de regressão, comparar os ajustes de diferentes modelos, testar termos de regressão específicos e testar igualdade entre médias.

Usando o teste F na ANOVA com um fator

Usar o teste F para determinar se as médias de grupo são iguais é apenas uma questão de incluir as variâncias corretas na razão. Na ANOVA com um fator, a estatística F é essa razão:

F = variação entre médias da amostra / variação dentro das amostras

A melhor maneira de entender essa razão é analisar um exemplo de ANOVA com um fator.

Vamos analisar quatro amostras de plástico para determinar se elas têm diferentes forças médias. Você pode baixar os dados amostrais se quiser acompanhar.(Se você não tiver o Minitab, poderá fazer o download de uma avaliação gratuita por 30 dias

No Minitab, escolha Estat> ANOVA> Um fator... Na caixa de diálogo, escolha "Força" como a resposta e "Amostra" como o fator. Aperte OK e a janela de sessão do Minitab exibirá a seguinte saída:

Numerador: Variação entre as médias amostrais

A ANOVA com um fator calculou uma média para cada uma das quatro amostras de plástico. As médias do grupo são: 11,203, 8,938, 10,683 e 8,838 Essas médias de grupo estão distribuídas em torno da média global para todas as 40 observações, que é 9,915. Se as médias dos grupos estão aglomeradas próximas à média global, suas variâncias é baixa. No entanto, se as médias do grupo estiverem mais afastadas da média global, a variância delas será maior.

Claramente, se queremos mostrar que as médias dos grupos são diferentes, quanto mais distantes estas médias estiverem umas das outras é de grande ajuda. Em outras palavras, queremos maior variabilidade entre as médias.

Imagine que realizamos duas ANOVAs com um fator, em que cada análise possui quatro grupos. O gráfico abaixo mostra o espalhamento das médias. Cada ponto representa a média de um grupo inteiro. Quanto mais os pontos estiverem espalhados, maior o valor da variabilidade no numerador da estatística-F.

Qual valor usamos para medir a variância entre as médias amostrais para o exemplo da resistência do plástico? Na saída da ANOVA com um fator, usaremos o quadrado médio ajustado (QM Aj) para o Fator, que é 14.540. Não tente interpretar esse número porque ele não fará sentido. É a soma dos desvios quadrados divididos pelo GL do fator. Apenas tenha em mente que quanto mais distante a média do grupo está, maior esse número se torna.

Denominador: Variação dentro das amostras

Também precisamos de uma estimativa da variabilidade dentro de cada amostra. Para calcular essa variância, precisamos calcular o quão distante cada observação está em relação à média do grupo, para todas as 40 observações. Tecnicamente é a soma dos desvios ao quadrado da diferença de cada observação em relação à média do grupo, dividido pelo s GL do erro.

Se as observações para cada grupo estiverem próximas da média deste grupo, a variação dentro das amostras será baixa. No entanto, se as observações para cada grupo estiverem mais longe da média de cada grupo, a variação dentro das amostras será maior.

No gráfico, o painel à esquerda mostra baixa variação nas amostras, enquanto o painel à direita mostra alta variação. Quanto mais dispersas as observações estiverem em relação á média do grupo, maior será o valor no denominador da estatística-F.

Se nosso objetivo for mostrar que as médias são diferentes, será bom que a variância dentro dos grupos seja baixa. Você pode pensar na variância dentro do grupo como o ruído de fundo que pode obscurecer a diferença entre as médias.

Para este exemplo de ANOVA com um fator, o valor que usaremos para a variância dentro das amostras é o QM Aj para o erro, que é 4,402. É chamado de "erro" porque é a variabilidade que não é explicada pelo fator.

A estatística F: Variação entre médias amostrais / Variação dentro das amostras

A estatística F é a estatística de teste para testes F. Em geral, uma estatística F é uma razão de duas quantidades que se espera que sejam aproximadamente iguais sob a hipótese nula, que por sua vez produz uma estatística F de valor aproximadamente 1.

A estatística F incorpora ambas as medidas de variabilidade discutidas acima. Vamos dar uma olhada em como essas medidas podem funcionar juntas para produzir valores F baixos e altos. Veja os gráficos abaixo e compare a largura do espalhamento das médias do grupo com a largura do espalhamento dentro de cada grupo.

O gráfico com o baixo valor-F mostra um caso em que as médias dos grupos estão próximas (baixa variabilidade) em relação à variabilidade dentro de cada grupo. O gráfico com o alto valor-F mostra um caso em que a variabilidade das médias dos grupos é grande em relação à variabilidade intragrupo. Para rejeitar a hipótese nula de que as médias do grupo são iguais, precisamos de um valor F alto.

Para nosso exemplo de força do plástico, usaremos o fator QM Aj para o numerador (14,540) e o erro QM Aj para o denominador (4,402), o que nos dá um valor F de 3,30.

O nosso valor F é alto o suficiente? Um único valor F é difícil de interpretar sozinho. Precisamos colocar nosso valor F em um contexto maior antes que possamos interpretá-lo. Para fazer isso, usaremos a distribuição F para calcular as probabilidades.

Distribuições F e Teste de hipóteses

Para a ANOVA com um fator, a razão entre a variabilidade entre os grupos e a variabilidade intragrupo segue uma distribuição F quando a hipótese nula é verdadeira.

Quando você faz uma ANOVA com um fator para um único estudo, obtém um único valor-F. No entanto, se extraíssemos várias amostras aleatórias do mesmo tamanho da mesma população e fizéssemos o mesmo ANOVA com um fator, obteríamos muitos valores F e poderíamos plotar uma distribuição de todos eles. Esse tipo de distribuição é conhecido como distribuição de amostragem.

Como a distribuição F assume que a hipótese nula é verdadeira, podemos colocar o valor F de nosso estudo na distribuição F para determinar quão consistentes são nossos resultados com a hipótese nula e calcular probabilidades.

A probabilidade que queremos calcular é a probabilidade de observar uma estatística F que é pelo menos tão alta quanto o valor que nosso estudo obteve. Essa probabilidade nos permite determinar quão comum ou raro nosso valor F é, sob a suposição de que a hipótese nula é verdadeira. Se a probabilidade for baixa o suficiente, podemos concluir que nossos dados são inconsistentes com a hipótese nula. A evidência nos dados amostrais é forte o suficiente para rejeitar a hipótese nula para toda a população.

Essa probabilidade que estamos calculando também é conhecida como valor-p!

Para plotar a distribuição F para nosso exemplo de força do plástico, utilizarei os gráficos de distribuição de probabilidade do Minitab. Para representar graficamente a distribuição F que é apropriada para nosso planejamento e tamanho de amostra específicos, precisaremos especificar o número correto de GL. Olhando para a saída do ANOVA com um fator, podemos ver que temos 3 GL para o numerador e 36 GL para o denominador.

O gráfico exibe a distribuição dos valores F que obteríamos se a hipótese nula fosse verdadeira e repetíssemos nosso estudo várias vezes. A área sombreada representa a probabilidade de observar um valor F que é pelo menos tão grande quanto o valor F obtido em nosso estudo. Os valores F caem dentro dessa região sombreada cerca de 3,1% do tempo quando a hipótese nula é verdadeira. Essa probabilidade é baixa o suficiente para rejeitar a hipótese nula usando nível de significância de 0,05. Podemos concluir que nem todas as médias do grupo são iguais.

Aprenda a interpretar corretamente o valor-p.

Avaliar médias usando a variação

O ANOVA usa o teste F para determinar se a variabilidade entre as médias do grupo é maior que a variabilidade das observações dentro dos grupos. Se essa proporção for suficientemente grande, você poderá concluir que nem todas as médias são iguais.

Isso nos traz de volta ao porque analisamos a variação para fazer julgamentos sobre as médias. Pense na questão: "As médias dos grupos são diferentes?" Você está implicitamente perguntando sobre a variabilidade das médias. Afinal, se as médias dos grupos não variam, ou não variam mais do que o acaso permite, então você não pode dizer que as médias são diferentes. E é por isso que você usa análise de variância para testar as médias.

# data[].attributes.attachment_link.title
Entendendo Análise de Variância (ANOVA) e o teste F

# data[].attributes.attachment_link.description
Alguns dos links relacionados podem conter informações em outros idiomas A análise de variância (ANOVA) pode determinar se as médias de três ou mais grupos são diferentes. A ANOVA usa testes F para testar estatisticamente a igualdade entre médias. Neste post, mostrarei como a ANOVA e os testes F funcionam, usando um exemplo de ANOVA com um fator.

# data[].attributes.headline
O que significa ter 95% de nível de confiança?

# data[].attributes.subject
O que significa ter 95% de nível de confiança?

# data[].attributes.body
https://support.minitab.com/pt-br/minitab/19/help-and-how-to/statistics/basic-statistics/supporting-topics/basics/what-is-a-confidence-interval/

# data[].attributes.attachment_link.readable_text
Um intervalo de confiança é uma amplitude de valores, derivados de estatísticas de amostras, que têm a probabilidade de conter o valor de um parâmetro populacional desconhecido. Devido à sua natureza aleatória, é improvável que duas amostras de uma determinada população irá render intervalos de confiança idênticos. Mas, se você repetir sua amostra várias vezes, uma determinada porcentagem dos intervalos de confiança resultantes conteria o parâmetro populacional desconhecido.

Aqui, a linha preta horizontal confiança representa o valor fixo da média desconhecida da população, . Os intervalos de confiança azuis verticais sobrepostos à linha horizontal contêm o valor da média da população. O intervalo de confiança vermelho totalmente abaixo da linha horizontal não contém esse valor. Um intervalo de confiança de 95% indica que 19 em 20 amostras (95%) da mesma população produzem intervalos de confiança contendo o parâmetro da população.

Use o intervalo de confiança para avaliar a estimativa do parâmetro populacional. Por exemplo, um fabricante quer saber se o comprimento médio dos lápis que ele produzem é diferente do comprimento alvo. O fabricante usa uma amostra aleatória de lápis e determina que o comprimento médio da amostra é 52 milímetros e o intervalo de confiança de 95% é (50, 54). Portanto, eles podem ter 95% de confiança de que o comprimento médio de todos os lápis está entre 50 e 54 milímetros.

O intervalo de confiança é determinado calculando-se uma estimativa de ponto e, depois, determinando sua margem de erro.

Estimativa de ponto

Este valor único estima um parâmetro populacional usando os seus dados amostrais.

Margem de erro

Quando você usa estatísticas para estimar um valor, é importante lembrar-se de que não importa quão bem seu estudo foi projetado, sua estimativa está sujeita a erros de amostragem aleatórios. A margem de erro quantifica esse erro e indica a precisão da sua estimativa.

Você provavelmente compreende a margem de erro como ela está relacionada aos resultados da pesquisa. Por exemplo, uma pesquisa política pode relatar que o índice de aprovação de um candidato é 55% com uma margem de erro de 5%. Isso significa que o real índice de aprovação é de +/- 5%, e está em algum ponto entre 50% e 60%.

Para um intervalo de confiança de dois lados, a margem de erro é a distância da estatística estimada para cada valor de intervalo de confiança. Quando um intervalo de confiança é simétrico, a margem de erro é metade da largura do intervalo de confiança. Por exemplo, o comprimento médio estimado de um eixo de comando é 600 mm e o intervalo de confiança varia de 599 a 601. A margem de erro é 1.

Quanto maior a margem de erro, maior é o intervalo, e menos certeza você pode ter sobre o valor da estimativa do ponto.

# data[].attributes.attachment_link.description
Um intervalo de confiança é uma amplitude de valores, derivados de estatísticas de amostras, que têm a probabilidade de conter o valor de um parâmetro populacional desconhecido. Devido à sua natureza aleatória, é improvável que duas amostras de uma determinada população irá render intervalos de confiança idênticos.

# data[].attributes.body
https://dplyr.tidyverse.org/

# data[].attributes.attachment_link.description
A fast, consistent tool for working with data frame like objects, both in memory and out of memory.

# data[].attributes.headline
Mais uma página útil para trabalhar com ggplot:

# data[].attributes.subject
Mais uma página útil para trabalhar com ggplot:

# data[].attributes.body
https://r4ds.had.co.nz/graphics-for-communication.html

# data[].attributes.attachment_link.readable_text
In exploratory data analysis, you learned how to use plots as tools for exploration. When you make exploratory plots, you know-even before looking-which variables the plot will display. You made each plot for a purpose, could quickly look at it, and then move on to the next plot. In the course of most analyses, you'll produce tens or hundreds of plots, most of which are immediately thrown away.

Now that you understand your data, you need to communicate your understanding to others. Your audience will likely not share your background knowledge and will not be deeply invested in the data. To help others quickly build up a good mental model of the data, you will need to invest considerable effort in making your plots as self-explanatory as possible. In this chapter, you'll learn some of the tools that ggplot2 provides to do so.

This chapter focuses on the tools you need to create good graphics. I assume that you know what you want, and just need to know how to do it. For that reason, I highly recommend pairing this chapter with a good general visualisation book. I particularly like The Truthful Art, by Albert Cairo. It doesn't teach the mechanics of creating visualisations, but instead focuses on what you need to think about in order to create effective graphics.

In this chapter, we'll focus once again on ggplot2. We'll also use a little dplyr for data manipulation, and a few ggplot2 extension packages, including ggrepel and viridis. Rather than loading those extensions here, we'll refer to their functions explicitly, using the :: notation. This will help make it clear which functions are built into ggplot2, and which come from other packages. Don't forget you'll need to install those packages with install.packages() if you don't already have them.

The easiest place to start when turning an exploratory graphic into an expository graphic is with good labels. You add labels with the labs() function. This example adds a plot title:

The purpose of a plot title is to summarise the main finding. Avoid titles that just describe what the plot is, e.g. "A scatterplot of engine displacement vs. fuel economy".

If you need to add more text, there are two other useful labels that you can use in ggplot2 2.2.0 and above (which should be available by the time you're reading this book):

You can also use labs() to replace the axis and legend titles. It's usually a good idea to replace short variable names with more detailed descriptions, and to include the units.

It's possible to use mathematical equations instead of text strings. Just switch "" out for quote() and read about the available options in ?plotmath:

1. Create one plot on the fuel economy data with customised title, subtitle, caption, x, y, and colour labels.

2. The geom_smooth() is somewhat misleading because the hwy for large engines is skewed upwards due to the inclusion of lightweight sports cars with big engines. Use your modelling tools to fit and display a better model.

3. Take an exploratory graphic that you've created in the last month, and add informative titles to make it easier for others to understand.

In addition to labelling major components of your plot, it's often useful to label individual observations or groups of observations. The first tool you have at your disposal is geom_text(). geom_text() is similar to geom_point(), but it has an additional aesthetic: label. This makes it possible to add textual labels to your plots.

There are two possible sources of labels. First, you might have a tibble that provides labels. The plot below isn't terribly useful, but it illustrates a useful approach: pull out the most efficient car in each class with dplyr, and then label it on the plot:

This is hard to read because the labels overlap with each other, and with the points. We can make things a little better by switching to geom_label() which draws a rectangle behind the text. We also use the nudge_y parameter to move the labels slightly above the corresponding points:

That helps a bit, but if you look closely in the top-left hand corner, you'll notice that there are two labels practically on top of each other. This happens because the highway mileage and displacement for the best cars in the compact and subcompact categories are exactly the same. There's no way that we can fix these by applying the same transformation for every label. Instead, we can use the ggrepel package by Kamil Slowikowski. This useful package will automatically adjust labels so that they don't overlap:

Note another handy technique used here: I added a second layer of large, hollow points to highlight the points that I've labelled.

You can sometimes use the same idea to replace the legend with labels placed directly on the plot. It's not wonderful for this plot, but it isn't too bad. ( theme(legend.position = "none") turns the legend off - we'll talk about it more shortly.)

Alternatively, you might just want to add a single label to the plot, but you'll still need to create a data frame. Often, you want the label in the corner of the plot, so it's convenient to create a new data frame using summarise() to compute the maximum values of x and y.

If you want to place the text exactly on the borders of the plot, you can use +Inf and -Inf. Since we're no longer computing the positions from mpg, we can use tibble() to create the data frame:

In these examples, I manually broke the label up into lines using "\n". Another approach is to use stringr::str_wrap() to automatically add line breaks, given the number of characters you want per line:

Note the use of hjust and vjust to control the alignment of the label. Figure 28.1 shows all nine possible combinations.

Remember, in addition to geom_text(), you have many other geoms in ggplot2 available to help annotate your plot. A few ideas:

Use geom_hline() and geom_vline() to add reference lines. I often make them thick ( size = 2) and white ( colour = white), and draw them underneath the primary data layer. That makes them easy to see, without drawing attention away from the data.

Use geom_rect() to draw a rectangle around points of interest. The boundaries of the rectangle are defined by aesthetics xmin, xmax, ymin, ymax.

Use geom_segment() with the arrow argument to draw attention to a point with an arrow. Use aesthetics x and y to define the starting location, and xend and yend to define the end location.

The only limit is your imagination (and your patience with positioning annotations to be aesthetically pleasing)!

The third way you can make your plot better for communication is to adjust the scales. Scales control the mapping from data values to things that you can perceive. Normally, ggplot2 automatically adds scales for you. For example, when you type:

ggplot2 automatically adds default scales behind the scenes:

Note the naming scheme for scales: scale_ followed by the name of the aesthetic, then _, then the name of the scale. The default scales are named according to the type of variable they align with: continuous, discrete, datetime, or date. There are lots of non-default scales which you'll learn about below.

The default scales have been carefully chosen to do a good job for a wide range of inputs. Nevertheless, you might want to override the defaults for two reasons:

You might want to tweak some of the parameters of the default scale. This allows you to do things like change the breaks on the axes, or the key labels on the legend.

You might want to replace the scale altogether, and use a completely different algorithm. Often you can do better than the default because you know more about the data.

There are two primary arguments that affect the appearance of the ticks on the axes and the keys on the legend: breaks and labels. Breaks controls the position of the ticks, or the values associated with the keys. Labels controls the text label associated with each tick/key. The most common use of breaks is to override the default choice:

You can use labels in the same way (a character vector the same length as breaks), but you can also set it to NULL to suppress the labels altogether. This is useful for maps, or for publishing plots where you can't share the absolute numbers.

You can also use breaks and labels to control the appearance of legends. Collectively axes and legends are called guides. Axes are used for x and y aesthetics; legends are used for everything else.

Another use of breaks is when you have relatively few data points and want to highlight exactly where the observations occur. For example, take this plot that shows when each US president started and ended their term.

Note that the specification of breaks and labels for date and datetime scales is a little different:

date_labels takes a format specification, in the same form as parse_datetime().

date_breaks (not shown here), takes a string like "2 days" or "1 month".

You will most often use breaks and labels to tweak the axes. While they both also work for legends, there are a few other techniques you are more likely to use.

To control the overall position of the legend, you need to use a theme() setting. We'll come back to themes at the end of the chapter, but in brief, they control the non-data parts of the plot. The theme setting legend.position controls where the legend is drawn:

You can also use legend.position = "none" to suppress the display of the legend altogether.

To control the display of individual legends, use guides() along with guide_legend() or guide_colourbar(). The following example shows two important settings: controlling the number of rows the legend uses with nrow, and overriding one of the aesthetics to make the points bigger. This is particularly useful if you have used a low alpha to display many points on a plot.

Instead of just tweaking the details a little, you can instead replace the scale altogether. There are two types of scales you're mostly likely to want to switch out: continuous position scales and colour scales. Fortunately, the same principles apply to all the other aesthetics, so once you've mastered position and colour, you'll be able to quickly pick up other scale replacements.

It's very useful to plot transformations of your variable. For example, as we've seen in diamond prices it's easier to see the precise relationship between carat and price if we log transform them:

However, the disadvantage of this transformation is that the axes are now labelled with the transformed values, making it hard to interpret the plot. Instead of doing the transformation in the aesthetic mapping, we can instead do it with the scale. This is visually identical, except the axes are labelled on the original data scale.

Another scale that is frequently customised is colour. The default categorical scale picks colours that are evenly spaced around the colour wheel. Useful alternatives are the ColorBrewer scales which have been hand tuned to work better for people with common types of colour blindness. The two plots below look similar, but there is enough difference in the shades of red and green that the dots on the right can be distinguished even by people with red-green colour blindness.

Don't forget simpler techniques. If there are just a few colours, you can add a redundant shape mapping. This will also help ensure your plot is interpretable in black and white.

The ColorBrewer scales are documented online at http://colorbrewer2.org/ and made available in R via the RColorBrewer package, by Erich Neuwirth. Figure 28.2 shows the complete list of all palettes. The sequential (top) and diverging (bottom) palettes are particularly useful if your categorical values are ordered, or have a "middle". This often arises if you've used cut() to make a continuous variable into a categorical variable.

When you have a predefined mapping between values and colours, use scale_colour_manual(). For example, if we map presidential party to colour, we want to use the standard mapping of red for Republicans and blue for Democrats:

For continuous colour, you can use the built-in scale_colour_gradient() or scale_fill_gradient(). If you have a diverging scale, you can use scale_colour_gradient2(). That allows you to give, for example, positive and negative values different colours. That's sometimes also useful if you want to distinguish points above or below the mean.

Another option is scale_colour_viridis() provided by the viridis package. It's a continuous analog of the categorical ColorBrewer scales. The designers, Nathaniel Smith and Stéfan van der Walt, carefully tailored a continuous colour scheme that has good perceptual properties. Here's an example from the viridis vignette.

Note that all colour scales come in two variety: scale_colour_x() and scale_fill_x() for the colour and fill aesthetics respectively (the colour scales are available in both UK and US spellings).

1. Why doesn't the following code override the default scale?

2. Change the display of the presidential terms by:

1. Combining the two variants shown above.

2. Improving the display of the y axis.

3. Labelling each term with the name of the president.

4. Adding informative plot labels.

5. Placing breaks every 4 years (this is trickier than it seems!).

3. Use override.aes to make the legend on the following plot easier to see.

There are three ways to control the plot limits:

1. Adjusting what data are plotted

2. Setting the limits in each scale

3. Setting xlim and ylim in coord_cartesian()

To zoom in on a region of the plot, it's generally best to use coord_cartesian(). Compare the following two plots:

You can also set the limits on individual scales. Reducing the limits is basically equivalent to subsetting the data. It is generally more useful if you want expand the limits, for example, to match scales across different plots. For example, if we extract two classes of cars and plot them separately, it's difficult to compare the plots because all three scales (the x-axis, the y-axis, and the colour aesthetic) have different ranges.

One way to overcome this problem is to share scales across multiple plots, training the scales with the limits of the full data.

In this particular case, you could have simply used faceting, but this technique is useful more generally, if for instance, you want spread plots over multiple pages of a report.

Finally, you can customise the non-data elements of your plot with a theme:

ggplot2 includes eight themes by default, as shown in Figure 28.3. Many more are included in add-on packages like ggthemes ( https://github.com/jrnold/ggthemes), by Jeffrey Arnold.

Many people wonder why the default theme has a grey background. This was a deliberate choice because it puts the data forward while still making the grid lines visible. The white grid lines are visible (which is important because they significantly aid position judgements), but they have little visual impact and we can easily tune them out. The grey background gives the plot a similar typographic colour to the text, ensuring that the graphics fit in with the flow of a document without jumping out with a bright white background. Finally, the grey background creates a continuous field of colour which ensures that the plot is perceived as a single visual entity.

It's also possible to control individual components of each theme, like the size and colour of the font used for the y axis. Unfortunately, this level of detail is outside the scope of this book, so you'll need to read the ggplot2 book for the full details. You can also create your own themes, if you are trying to match a particular corporate or journal style.

There are two main ways to get your plots out of R and into your final write-up: ggsave() and knitr. ggsave() will save the most recent plot to disk:

ggsave ( "my-plot.pdf" ) #> Saving 7 x 4.33 in image

If you don't specify the width and height they will be taken from the dimensions of the current plotting device. For reproducible code, you'll want to specify them.

Generally, however, I think you should be assembling your final reports using R Markdown, so I want to focus on the important code chunk options that you should know about for graphics. You can learn more about ggsave() in the documentation.

The biggest challenge of graphics in R Markdown is getting your figures the right size and shape. There are five main options that control figure sizing: fig.width, fig.height, fig.asp, out.width and out.height. Image sizing is challenging because there are two sizes (the size of the figure created by R and the size at which it is inserted in the output document), and multiple ways of specifying the size (i.e., height, width, and aspect ratio: pick two of three).

I only ever use three of the five options:

I find it most aesthetically pleasing for plots to have a consistent width. To enforce this, I set fig.width = 6 (6") and fig.asp = 0.618 (the golden ratio) in the defaults. Then in individual chunks, I only adjust fig.asp.

I control the output size with out.width and set it to a percentage of the line width. I default to out.width = "70%" and fig.align = "center". That give plots room to breathe, without taking up too much space.

To put multiple plots in a single row I set the out.width to 50% for two plots, 33% for 3 plots, or 25% to 4 plots, and set fig.align = "default". Depending on what I'm trying to illustrate (e.g. show data or show plot variations), I'll also tweak fig.width, as discussed below.

If you find that you're having to squint to read the text in your plot, you need to tweak fig.width. If fig.width is larger than the size the figure is rendered in the final doc, the text will be too small; if fig.width is smaller, the text will be too big. You'll often need to do a little experimentation to figure out the right ratio between the fig.width and the eventual width in your document. To illustrate the principle, the following three plots have fig.width of 4, 6, and 8 respectively:

If you want to make sure the font size is consistent across all your figures, whenever you set out.width, you'll also need to adjust fig.width to maintain the same ratio with your default out.width. For example, if your default fig.width is 6 and out.width is 0.7, when you set out.width = "50%" you'll need to set fig.width to 4.3 (6 * 0.5 / 0.7).

When mingling code and text, like I do in this book, I recommend setting fig.show = "hold" so that plots are shown after the code. This has the pleasant side effect of forcing you to break up large blocks of code with their explanations.

To add a caption to the plot, use fig.cap. In R Markdown this will change the figure from inline to "floating".

If you're producing PDF output, the default graphics type is PDF. This is a good default because PDFs are high quality vector graphics. However, they can produce very large and slow plots if you are displaying thousands of points. In that case, set dev = "png" to force the use of PNGs. They are slightly lower quality, but will be much more compact.

It's a good idea to name code chunks that produce figures, even if you don't routinely label other chunks. The chunk label is used to generate the file name of the graphic on disk, so naming your chunks makes it much easier to pick out plots and reuse in other circumstances (i.e. if you want to quickly drop a single plot into an email or a tweet).

The absolute best place to learn more is the ggplot2 book: ggplot2: Elegant graphics for data analysis. It goes into much more depth about the underlying theory, and has many more examples of how to combine the individual pieces to solve practical problems. Unfortunately, the book is not available online for free, although you can find the source code at https://github.com/hadley/ggplot2-book.

Another great resource is the ggplot2 extensions gallery https://exts.ggplot2.tidyverse.org/gallery/. This site lists many of the packages that extend ggplot2 with new geoms and scales. It's a great place to start if you're trying to do something that seems hard with ggplot2.

# data[].attributes.attachment_link.description
In exploratory data analysis, you learned how to use plots as tools for exploration. When you make exploratory plots, you know-even before looking-which variables the plot will display. You made each plot for a purpose, could quickly look at it, and then move on to the next plot.

# data[].attributes.headline
Livro da Natalia Levshina sobre noções de estatística utilizando o R para análise linguística.  

# data[].attributes.subject
Livro da Natalia Levshina sobre noções de estatística utilizando o R para análise linguística.  

# data[].attributes.attachment_link.title
Natalia Levshina - How to do Linguistics with R_ Data exploration and statistical analysis-John Benjamins (2015)

# data[].attributes.headline
Para interface de análise estatística diferente, podem usar também a extensão de R commander: plot.new(); library(Rcmdr)

# data[].attributes.subject
Para interface de análise estatística diferente, podem usar também a extensão de R commander: plot.new(); library(Rcmdr)

# data[].attributes.body
Livro de introdução a R que Danilo sugeriu

# data[].attributes.body
O site sobre as funções de ggplot que Danilo recomendou

# data[].attributes.attachment_link.title
Create Elegant Data Visualisations Using the Grammar of Graphics

# data[].attributes.attachment_link.description
A system for declaratively creating graphics, based on “The Grammar of Graphics”. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.

# data[].attributes.headline
Grupo no Facebook sobre R para Linguistas

# data[].attributes.subject
Grupo no Facebook sobre R para Linguistas

# data[].attributes.body
Há alguns anos, a professora Livia Oushiro criou um grupo no Facebook com o intuito de trocar informações, dicas, ajudas e afins sobre o uso da plataforma R aplicada à área da Linguística.

# data[].attributes.attachment_link.description
R para Linguistas has 652 members. Grupo de discussão sobre a plataforma R aplicado a análises linguísticas. Este é um espaço para compartilhar materiais, dúvidas e descobertas sobre o programa.

# data[].attributes.headline
script para gerar um excel de uma tabela ou dataframe gerada em R:

# data[].attributes.subject
script para gerar um excel de uma tabela ou dataframe gerada em R:

# data[].attributes.body
library("writexl")
write_xlsx(palWil,"C:/Users/marij/Desktop//palWil.xlsx")

# data[].attributes.headline
Material de Introdução à Estatística da profa. Livia Oushiro

# data[].attributes.subject
Material de Introdução à Estatística da profa. Livia Oushiro

# data[].attributes.headline
o que é um intercept em uma análise de regressão linear?

# data[].attributes.subject
o que é um intercept em uma análise de regressão linear?

# data[].attributes.body
https://statisticsbyjim.com/regression/interpret-constant-y-intercept-regression/#more-847