Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Statistical Analysis: an Introduction using R/Chapter 2

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

4 Data is the life blood of statistical analysis. A recurring theme in this book is that most analysis consists of constructing sensible statistical models to explain the data that has been observed. This requires a clear understanding of the data and where it came from. It is therefore important to know the different types of data that are likely to be encountered. Thus in this chapter we focus on different types of data, including simple ways in which they can be examined, and how data can organised into coherent datasets. h4 right none #8888FF clear: none; nodrop R topics in Chapter 2 The R examples used in this chapter are intended to introduce you to the nuts and bolts of R, so may seem dry or even overly technical compared to the rest of the book. However, the topics introduced here are essential to understand how to use R and it is particularly important to understand them. They assume that you are comfortable with the concepts of assignment (i.e. storing objects) and functions, as detailed previously. Variables The simplest sort of data is just a collection of measurements, each measurement being a single "data point". In statistics, a collection of single measurements of the same sort is commonly known as a variable, and these are often given a nameThe convention (which is followed here) is to write variable names in italics. Variables usually have a reasonable amount of background context associated with them: what the measurements represent, why and how they were collected, whether there are any known omissions or exceptional points, and so forth. Knowing or finding out this associated information is an essential part of any analysis, along with examination of the variables (e.g. by plotting or other means). Single variables in R h4 right #8888FF Vectors ../R/Vectors h4 right #8888FF Accessing elements of vectors ../R/Accessing elements of vectors h4 right #8888FF Logical operations ../R/Logical operations h4 right #8888FF Missing data ../R/Missing data Measurement values One important feature of any variable is the values it is allowed to have. For example, a variable such as sex can only take a limited number of values ('Male' and 'Female' in this instance), whereas a variable such as humanHeight can take any numerical value between about 0 and 3 metres. This is the sort of obvious background information that cannot necessarily be inferred from the data, but which can be vital for analysis. Only a limited amount of this information is usually fed directly into statistical analysis software. As always, it's very important to take account of such background information. This can be usually done using that commodity - unavailable to a computer - known as common sense. For example, a computer could be used to perform an analysis of human height without realising that one person has been recorded as (say) 175, rather than 1.75, metres tall. A computer can blindly perform analysis on this variable without noticing the error, even though it is glaringly obvious to a humanSimilar examples are given in Chatfield ****. That's one of the primary reasons that it is important to plot data before analysis. Categorical versus quantitative variables Nevertheless, a few bits of information about a variable can (indeed, often must) be given to analysis software. Nearly all statistical software packages require you, at a minimum, to distinguish between categorical variables (e.g. sex) in which each data point takes one of a fixed number of pre-defined "levels", and quantitative variables (e.g. humanHeight) in which each data point is a number on a well-defined scale. Further examples are given in Table 2.1. This distinction is important even for such simple analyses as taking an average: a procedure which is meaningful for a quantitative variable, but rarely for a categorical variable (what is the "average" sex of a 'male' and a 'female'?). + Table 2.1 Examples of types of variables. Many of these variables are used later in this book. Categorical (also known as "qualitative" variables or "factors") The variable sex where each data point is the sex of a human (i.e. the levels are 'Male' or 'Female') The variable class, where each data point is the class of a passenger on a ship (the levels being '1st', '2nd', or '3rd') Quantitative (also known as "numeric" variables or "covariates") The variable weightChange, where each point is the weight change of an anorexic patient over a fixed period. The variable landArea, where each data point is a positive number giving the area of a piece of land. The variable shrimp, where each data point is the determination of the percentage of shrimp in a preparation of shrimp cocktail (!) The variable deathsPerYear, where data point is a count of a number of individuals who have died from a particular cause in a particular year. The variable cases, where each data point is a count of the number of people in a particular group who have a specific disease. This may be meaningless unless we also have some measure of the group size. This can be done by via another variable (often labelled controls) indicating the number of people in each group who have not developed the disease (grouped case/control studies of this sort are common in areas such as medicine). The variable temperatureF, where each data point is an average monthly temperature in degrees Fahrenheit. The variable direction, where each data point is a compass direction in degrees. It is not always immediately obvious from the plain data whether a variable is categorical or quantitative: often this judgement must be made by careful consideration of the context of the data. For example, a variable containing numbers 1, 2, and 3 might seem to be a numerical quantity, but it could just as easily be a categorical variable describing (say) a medical treatment using either drug 1, drug 2, or drug 3. More rarely, a seemingly categorical variable such as colour (levels 'blue', 'green', 'yellow', 'red') might be better represented as a numerical quantity such as the wavelength of light emitted in an experiment. Again, it's your job to make this sort of judgement, on the basis of what you are trying to do. Borderline categorical/quantitative variables Despite the importance of the categorical/quantitative distinction (and its prominence in many textbooks), reality is not always so clear-cut. It can sometimes be reasonable to treat categorical variables as quantitative, or vice versa. Perhaps the commonest case is when the levels of a categorical variable seem to have a natural order, such as the class variable in Table 2.1, or the Likert scale often used in questionnaires. In rare and specific circumstances, and depending on the nature of the question being asked, there may be rough numerical values that can be allocated to each level. For example, maybe a survey question is accompanied by a visual scale on which the Likert categories are marked, from 'absolutely agree' to 'absolutely disagree'. In this case it may be justifiable to convert the categorical variable straight into to a quantitative one. More commonly, the order of levels is known, but exact values cannot be generally agreed upon. Such categorical variables can be described as ordinal or ranked, as opposed ones such as gender or professedReligion which are purely nominal. Hence we can recognise two major types of categorical variable: ordered ("ordinal") and unordered ("nominal"), as illustrated by the two examples in Table 2.1. Classification of quantitative variables Although the categorical/quantitative division is the most important one, we can further subdivide each type (as we have already seen when discussing categorical variables) . The most commonly taught classification is due to Stevens (1946). As well as dividing categorical variables into ordinal and nominal types, he classified quantitative variables into two types, interval or ratio, depending on the nature of the scale that was used. To this classification can be added circular variables. Hence classifying quantitative variables on the basis of the measurement scale leads to three subdivision (as illustrated by the subdivisions in Table 2.1): Ratio data is the most commonly encountered. Examples include distances, lengths of time, numbers of items, etc. These variables are measured on a scale with a natural zero point; because we can work with exclusively positive integers. Interval data is measured on a scale where there is no natural zero point. The most common examples are temperature (in degrees Centigrade or Fahrenheit) and calendar date. Since the zero point on the scale is essentially arbitrary, The name comes from the fact that while ratios are not meaningful, intervals are. E.g. means that **** Circular data is measured on a scale which "wraps around", such as Direction, TimeOfDay, Logitude etc. *** The Stevens classification is not the only way to categorise quantitative variables. Another sensible division recognises the difference between continuous and discrete measurements. Specifically, quantitative variables can represent either Continuous data, in which it makes sense to talk about intermediate values (e.g. 1.2 hours, 12.5%, etc.). This includes cases where data have been rounded ***. "Discrete data", where intermediate values are nonsensical (e.g. doesn't make much sense to talk about 1.2 deaths, or 2.6 cancer cases in a group of 10 people). Often these are counts of things: this is sometime known as meristic data. In practice, discrete data are often treated as continuous, especially when the units into which they are divided are relatively small. For example, the population size of different countries is theoretically discrete (you can't have half a person), but the values are so huge that it may be reasonable to treat such data as continuous. However, for small values, such as the number of people in a household, the data are rather "granular", and the discrete nature of values becomes very apparent. One common result of this is the presence of multiple repeated values (e.g. there will be a lot of 2 person households in most data sets). A third way of classifying quantitative variables depends on whether the scale has upper or lower bounds, or even both. bounded at one end (e.g. landArea cannot be below 0), at both ends (e.g. percentages cannot be less then 0 or greater than 100). Also see censored data *** unbounded (weightLoss). Most important is circular - often requires very different analytical tools. Often best to make linear in some way (e.g. difference from a fixed direction). Interval data cannot use ratios (division). Rather rare Bounds: very common to have lower bound. Unusual to have only an upper bound. Both often indicates a percentage. - often treated by transformation (e.g. log) Count data: if multiple identical values, can affect plotting etc. If true independent counts, indicates error function. The distinctions between the different types of variables are summarised in Figure ***. Note that it is also common to Independence of data points Does the actual value cause correllations in "surrounding" values (e.g. time series), or do both reflect some common association (e.g. blocks/heterogeneity). Time series Spatial data Blocks Incorporating information Time series, other sources of non-independence h4 right #8888FF Factors ../R/Factors h4 right #8888FF Matrices and Arrays ../R/Matrices h4 right #8888FF Lists ../R/Lists Visualising a single variable Before carrying out a formal analysis, you should always perform an Initial Data Analysis, part of which is to inspect the variables that are to be analysed. If there are only a few data points, the numbers can be scanned by eye, but normally it is easier to inspect data by plotting. Scatter plots, such as those in Chapter 1, are perhaps the most familiar sort of plot, and are useful for showing patterns of association between two variables. These are discussed later in this chapter, but in this section we first examine the various ways of visualising a single variable. Plots of a single variable, or univariate plots are particularly used to explore the distribution of a variable; that is its shape and position. Apart from initial inspection of data, one very common use of these plots is to look at the residuals (see Figure 1.2): the unexplained part of the data that remains after fitting a statistical model. Assumptions about the distribution of these residuals are often checked by plotting them. The plots which follow illustrate a few of the more common types of univariate plot. The classic text is Tufte (cite: the visual display of quantitative information). Categorical variables For categorical variables, the choice of plots is quite simple. The most basic plots simply involve counting up the data points at each level. Figure 2.1(a) displays these counts as a bar chart; another possibility is to use points as in Figure 2.1(b). In the case of gender, the order of the levels is not important: either 'male' or 'female' could come first. In the case of class, the natural order of the levels is used in the plot. In the extreme case, where intermediate levels might be meaningful, or where you wish to emphasise the pattern between levels, it may be reasonable to connect points by lines. For illustrative purposes, this has been done in Figure 2.1(b), although the reader may question whether it is appropriate in this instance. plot(1:length(Gender), Gender, yaxs="n"); axis(2, 1:2, levels(Gender), las=1) In some cases we may be interested in the actual sequence of data points. This is particularly so for time series data, but may also be relevant elsewhere. For instance, in the case of gender, the data was recorded in the order that each child was born. If we think that the preceeding birth influences the following birth (unlikely in this case, but just within the realm of possibility if pheremones are involved), then we might want to do Symbol-by-Symbol plot . If we are looking for associations with time, however, then a bivariate plot may be more appropriate ***, or there are particular features of the data that we are interested in (e.g. repeat rate), then other possibilities exist (doi:10.1016/j.stamet.2007.05.001).See chapter on time series Quantitative variables + Table 2.2: Land area (km2) of the 50 states of the USA landArea Alabama133666Alaska1527463Arizona295022Arkansas137538California411012Colorado269998Connecticut12973Delaware5327Florida151669Georgia152488Hawaii16705Idaho216411Illinois146075Indiana93993Iowa145790Kansas213062Kentucky104622Louisiana125673Maine86026Maryland27394Massachusetts21385Michigan150778Minnesota217735Mississippi123583Missouri180485Montana381085Nebraska200017Nevada286297New Hampshire24097New Jersey20295New Mexico315113New York128401North Carolina136197North Dakota183021Ohio106764Oklahoma181089Oregon251179Pennsylvania117411Rhode Island3144South Carolina80432South Dakota199550Tennessee109411Texas692404Utah219931Vermont24887Virginia105710Washington176616West Virginia62628Wisconsin145438Wyoming253596 + Table 2.3: A classic data set of the number of accidental deaths by horse-kick in 14 cavalry corps of the Prussian army from 1875-1894This dataset was collected by the Russian economist von Bortkiewicz, in 1898, to illustrate the pattern seen when events occur independently of each other (this is known as a Poisson distribution). The table here gives the total number of deaths summed over all 14 corps. For the full dataset, broken down into corp, see ../Datasets deathsPerYear 18753187651877718789187910188018188161882141883111884918855188611188715188861889111890171891121892151893818944 A quantitative variable can be plotted in many more ways than a categorical variable. Some of the most common single-variable plots are discussed below, using the land area of the 50 US states as our example of a continuous variable, and a famous data set of the number of deaths by horse kick as our example of a discrete variable. These data are tabulated in Tables 2.2 and 2.3 Some sorts of data consist of many data points with identical values. This is particularly true for count data where there are low numbers of counts (e.g. number of offspring). There are 3 things we might want to look for in these sorts of plots points that seem extreme in some way (these are known as outliers). Outliers often reveal mistakes in data collection, and even if they don't, they can have a disproportionate effect on further analysis. If it turns out that they aren't due to an obvious mistake, one option is to remove them from the analysis, but this causes problems of its own/ shape & position of the distribution (e.g. normal, bimodal, etc.) similarity to known distributions (QQ) We'll keep the focus mostly on the variable "landArea" *** Figure 2.3: Basic plots for continuous quantitative variablesthumb|none|450px|(a) 1D scatterplotR-US_state_areas-1D_jitter.svg R-US_state_areas-1D+quartiles.svg (b) 1D scatterplot (jittered) (b) Colours illustrate upper (red) and lower (green) quartiles thumb none 450pxR-US_state_areas-basicboxplot.svg R-US_state_areas-basicboxplot+colour.svg (c) Basic boxplot. The box displays the median and upper and lower quartiles, while the "whiskers" show the full range (from the minimum to the maximum) of the data. (c) Boxplot coloured to correspond to Figure 2.3b thumb none 450px(d) Sophisticated boxplot. Outliers have been excluded from the whiskers, and plotted separately. The notch in the box gives an idea of our confidence in the value of the median.|thumb|none|450px The simplest way to represent quantitative data is to plot the points on a line, as in Figure 2.3(a). This is often called a dot plot, although this is also sometimes used to describe a number of other types of plot (e.g. Figure 2.7)Authors such as Wild & Seber call it a dot plot, but R uses the term "dotplot" to refer to a Cleveland (1985) dot-plot as shown in Figure 2.1(b). Other authors (***) specifically use it to refer to a sorted ("quantile") plot as used in Figure *** (cite) . To avoid confusion, it may be best to call it a one-dimensional scatterplot. As well as simplicity, there are two advantages to a 1D scatterplot All the information present in the data is retained. Outliers are easily identified. Indeed, it is often useful to be able to identify which data points are outliers. Some software packages allow you to identify points interactively (e.g. by clicking points on the plot). Otherwise, points can be labelled, as has been done for some outlying points in Figure 2.3aLabels often obscure the plot, so For plots intended only for viewing on a computer, it is possible to print labels in a size so small that they can only be seen when zooming in.. One dimensional scatterplots do not work so well for large datasets. Figure 2.3(a) consists of only 50 points. Even so, it is difficult to get an overall impression of the data, to (as the saying goes) "see the wood for the trees". This is partly because some points lie almost on top of each other, but also because of the sheer number of closely placed points. It is often the case that features of the data are best explored by summarising it in some way. Figure 2.3(b) shows a step on the way to a better plot. To alleviate the problem of points obscuring each other, they have been displaced, or jittered sideways by a small, random amount. More importantly, the data have been summarised by dividing into quartiles (and coloured accordingly, for ease of explanation). The quarter of states with the largest area have been coloured red. The smallest quarter of states have been coloured green. More generally, we can talk about the quantiles of our dataThere a many different methods for calculating the precise value of a quantile, when it lies between two points. See Hyndman and Fan (1996). The red line represents the 75% quantile: 75% of the points lie below it. The green line represents the 25% quantile: 25% of the points lie below it. The distance between these lines is known as the Interquartile Range (IQR), and is a measure of the spread of the data. The thick black line has a special name: the median. It marks the middle of the data, the 50% quantile: 50% of the points lie above, and 50% lie below. A major advantage of quantiles over other summary measures is that they are relatively insensitive to outliers, or changes in scale ****. Figure 2.3(c) is a coloured version of a widely used statistical summary plot: the boxplot. Here it has been coloured to show the correspondence to Figure 2.3(b). The box marks the quartiles of the data, with the median marked within the box. If the median is not positioned centrally within the box, this is often an indicator that the data are skewed in some way. The lines on either side of the box are known as "whiskers", and summarise the data which lies outside of the upper and lower quartiles. In this case, the whiskers have simply been extended to the maximum and minimum observed values. Figure 2.3(d) is a more sophisticated boxplot of the same data. Here, notches have been drawn on the box: these are useful for comparing the medians in different boxplots. The whiskers'' have been shortened so that they do not include points considered as outliers. There are various ways of defining these outliers automatically. This figure is based on a convention that considers outlying points as those more than one and a half times the IQR from either side of the box. However it is often more informative to identify and inspect interesting points (including outliers) by visual inspection. For example, in Figure 2.1a it is clear that Alaska and (to a lesser extent) Texas are unusually large states, but that California (identified as an outlier by this automatic procedure) is not so set-apart from the rest. Figure 2.4: Basic plots for discrete quantitative variablesthumb|none|(a) Jitteredthumb|none|(b) Stacked (or see line equivalent in fig 2.5a)thumb|none|(c) Boxplots are also reasonable for discrete datathumb|none|(d) Points merged. Here the area (not width or height) of each point is relative to the number of plotting points at each location. It is more difficult to judge the exact numbers, and so is more useful in plots such as Snow's modified cholera plot (Chapter 1), where locations are given more weight depending on the number of points at each *** One problem with plotting on a single line is that, if points are repeated, there ***. This is particularly problematic for discrete data. NB, there is no particular reason (or established convention) for these plots to be vertical. Figure 2.2 shows . The stacked plot (Figure 2.4d) is similar to a histogram (Figure 2.5). Figure 2.5: Histogramsthumb|none|(a) Histogram-like line plot (compare to Fig 2.4b)|360pxR-horsekick_totals-histogram.svg R-horsekick_totals-histogram+quartiles.svg (b) As a histogram, years merged in 2s (b) Colours illustrate upper (red) and lower (green) quartiles thumb none 360pxR-US_state_areas-histogram.svg R-US_state_areas-histogram+points.svg (c) Histogram for continuous data (c) Actual points marked thumb none 360pxR-US_state_areas-histogram_hires.svg R-US_state_areas-histogram_hires+points.svg (d) Smaller bin widths (d) Actual points marked thumb none 360px This gives another way of picturing the median & other quantiles: as dividing the area into sections *** Figure 2.6: Density plotsthumb|none|(a) Kernel density plot|360pxthumb|none|(b) Kernel density plot (can be misleading for e.g. uniform distributions)|360px We can space out the points along the other axis. For example, if the order of points in the dataset is meaningful, we can just plot each point in turn. This is true for whatsit's horse-kick data. The data by year are plotted in Figure 2.6. Figure 2.7: Ordering data pointsthumb|none|(a) Simple time series plot (i.e. sorted by date/time)|360pxR-horsekick_totals-quantileplot.svg R-horsekick_totals-quantileplot+quartiles.svg (b) Quantile plot (the same points ordered by size) (b) Quartiles illustrated with corresponding boxplot thumb none 360pxthumb|none|(c) Empirical cumulative distribution function (as (b) but with axes swapped and rescaled)|360px One thing we can always do is to sort the data points by their value, plotting the smallest first, etc. This is seen in Figure 2.3b. If all the data points were equally spaced (and excluded each other****), we would see a straight line. The plot for the logged variables shows that this transformation has evened out the spacing somewhat. This is called a quantile plot, for the following reason when the axes are swapped, this is called the empirical cumulative distribution function. The unswapped data is useful for understanding qq plots. Also for understanding quantiles. median, etc. Transformations We could put a scale break in, but a better option is usually to transform the variable. Figure 2.8: The effect of log transformationR-US_state_areas-1D_log.svg R-US_state_areas-1D_log+extras.svg noneR-US_state_areas-boxplot_log.svg R-US_state_areas-boxplot_log+extras.svg nonenonenone Sometimes, plotting on a different scale (e.g. a logarithmic scale) can be more informative. We can visualise this either as a plot with a non-linear (e.g. logarithmic) axis, or as a conventional plot of a transformed''' variable (e.g. a plot of log(my.variable) on a standard, linear axis). Figure 2.1(b) illustrates this point: the left axis marks the state areas, the right axis marks the logarithm of the state areas. This sort of rescaling can highlight quite different features of a variable. In this case, it seems clear that there are a batch of nine states which seem distinctly smaller than most, and while Alaska still seems extraordinarily large, Texas does not seem so unusual in that respect. This is also reflected by the automatic labelling of outliers in the log-transformed variable. It is particularly common for smaller numbers to have greater resolution. As discussed in later chapters ***, logarithmic scales are particularly useful for multiplicative data ***. Figure 2.8: The effect of square root transformationR-US_state_areas-1D_sqrt.svg R-US_state_areas-1D_sqrt+extras.svg noneR-US_state_areas-boxplot_sqrt.svg R-US_state_areas-boxplot_sqrt+extras.svg nonenonenone There are other common transformations, for example, the square-root transformation (often used for count data). This may be more appropriate for state areas, if the limiting factor for state size is (e.g.) the distance across the state, or factors associated with it (e.g. the length of time to cross from one side to another). Figure 2.1c shows a sqrt rescaling of the data. You can see that in some sense this is less extreme than the log transformation... h4 right #8888FF Univariate plots ../R/Univariate plots Datasets Multiple variables in a table. Notation. most packages do this. :Statistical_Analysis:_an_Introduction_using_R/R/Data frames :Statistical_Analysis:_an_Introduction_using_R/R/Reading in data Bivariate plotting Quantitative versus quantitative Scatter plots problems with overplotting? Sunflowerplots etc. Quantitative versus categorical Vioplots (&boxplots) Categorical versus categorical Mosaicplots :Statistical_Analysis:_an_Introduction_using_R/R/Bivariate plots Notes References Carifio, J. & Perla, R. (2007). Ten Common Misunderstandings, Misconceptions, Persistent Myths and Urban Legends about Likert Scales and Likert Response Formats and their Antidotes. Journal of Social Sciences, 2, 106-116. http://www.scipub.org/fulltext/jss/jss33106-116.pdf Chapter 3 Chapter 1