Descriptive Statistics and Graphing with R
In this tutorial we shall learn to perform simple statistical
analysis and plotting of data with R. The parts involving
astronomical information are based on the notes by
Prof. David Hunter.
Getting astronomical data
The astronomical community has a vast complex of on-line
databases. Many databases are hosted by data centres such as the
Donnees astronomiques de Strasbourg (CDS), the NASA/IPAC Extragalactic Database
(NED), and the Astrophysics
Data System (ADS).
The Virtual Observatory (VO) is developing new flexible tools for
accessing, mining and combining datasets at distributed
the Web sites for the international,
European, and U.S. VO for information on recent
developments. The VO Web
Schools, and Core Applications
provide helpful entries into these new capabilities.
We initially treat here only input of tabular data such as catalogs of
astronomical sources. We give two examples of interactive
of tabular data. One of the multivariate tabular datasets used
a dataset of stars observed with the European Space Agency's Hipparcos
satellite during the 1990s. It gives a table with 9 columns and
2719 rows giving Hipparcos stars lying between 40 and 50 parsecs from
the Sun. The dataset was acquired using CDS's Vizier Catalogue Service as
- In Web browser, go to
Set Max Entries to 9999, Output layout ASCII table
"Compute r" and "Compute Position" buttons
Set parallax constraint "20 .. 25" to gives stars between 40 and 50 pc
Retrieve 9 properties: HIP, Vmag, RA(ICRS), DE(ICRS), Plx, pmRA, pmDE, e_Plx, and B-V
- Use ASCII editor to trim header to one line with variable
- Trim trailer
- Indicate missing values by NA.
- Save ASCII file on disk for ingestion into R
Reading the data into R
Let us assume that the data set is in
We have already learned how to use the absolute path
F:\astro\HIP.dat to load the data set into R. Now
we shall learn a two step process that is usually easier.
First navigate to the correct folder/directory
setwd("F:/astro") #notice the forward slash
getwd() #just to make sure
setwd means "set working
Now load the data set
hip = read.table("HIP.dat", header = TRUE, fill = TRUE)
After the loading is complete we should make sure that things are
as they should be. So we check the size of the data set, the
The advantage of using |
setwd is that you have to type
the name of the folder/directory only once. All files
(data/script) in that folder can then be referred to by just the
Let us take a look at the first 3 rows of the data set.
There is a variable called RA in the data set. It corresponds to
column 3 in the data set. To see its values
you may use either
What command should you use to see the first 2 columns?
Incidentally, the first column is just an index variable without
any statistical value. So let us get rid of it.
hip = hip[,-1]
The following diagram shows four different data sets along a
Notice that the points in the red data set (topmost) and the
black data set (third from top) are more or less around the same
centre point (approximately 2). The other two data sets are more
or less around the value 0. We say that the red and black data
sets have the same central tendency, while the other data
sets have a different central tendency.
Again, notice that the points in the red and blue data sets (the topmost two)
are tightly packed, while the other two data sets have larger
spreads. We say that the bottom two data sets have larger
dispersion than the top two.
|Four data sets shown along a number line
When summarising a data set we are primarily interested in
learning about its central tendency and dispersion. The central
tendency may be obtained by either the
median. The median is the most central value of a
To find these for all the variables in
our data set we
median function on the columns.
Have you noticed the mean of the last variable? It is
NA or ``Not Available'', which is hardly surprising since
not all the values for that variable were present in the original
data set. We shall learn later how to deal with missing
median of all the variables.
Possibly the simplest (but not the best) way to get an idea of the
dispersion of a data set is to compute
the min and max. R has the functions
max for this purpose.
In fact, we could have applied the
range function to
find both min and max in a single line.
The most popular way to find the dispersion of a data set is by
using the variance (or its positive square root, the
standard deviation). The formula is
where is the mean of the data. The function
sd compute the variance and standard
Another popular measure of dispersion is
absolute deviation (or MAD) is proportional to the median
absolute distances of the values from the median. It is given by
the following formula.
The constant of proportionality happens to be the magic number
1.4826 for some technical reason.
For example, if we have just 3 values 1,2 and 4, then
- the median is 2,
- absolute deviations from median are |1-2|=1, |2-2|=0 and
- median of the absolute deviations is 1,
- MAD = 1.4826.
mad computes this.
We want to compute both the median and MAD using one function. So
f = function(x) c(median(x), mad(x))
There is yet another way to measure the dispersion of a data
set. This requires the concept of a quantile. Some
examinations report the grade of a student in the form of
percentiles. A 90-percentile student is one whose
grade is exceeded by 10% of all the students. The quantile
is the same concept except that it talks about proportions instead
of percentages. Thus, the 90-th percentile is 0.90-th quantile.
What will be the result of the following?
The R function
The median of a data set is the most central value. In other
words, exactly half of the data set exceeds the median. So for
what value of p is the median the p-th quantile?
quantile (not surprisingly!) computes
The 0.25-th and 0.75-th quantiles are called the first
quartile and the third quartile, respectively.
What is the second quartile?
The difference between first and third quartiles is another
measure of the dispersion of a data set, and is called the
InterQuartile Range (IQR).
There is function called
summary that computes quite a
few of the summary statistics.
Look up the online help for the functions
cor to find out what they do. Use them to find the
covariance and correlation between
Handling missing values
So far we have ignored the
NA problem completely. The next
exercise shows that this is not always possible in R.
var computes the variance. Try
applying it to the columns of our data set.
NA denotes missing data in R. It is like a different kind of
number in R (just like Inf, or NaN). Any mathematics with
NA + 2
NA - NA
is.na checks for presence of
NAs in a
vector or matrix.
x = c(1,2,NA)
any reports TRUE if there is at least one
TRUE in its argument vector. The
combination is very useful. So let us make a function out of
hasNA = function(x) any(is.na(x))
This exercise shows that only the last variable has
What is the consequence of this?
in it. So
naturally the following commands
NA. But often we want to apply the function on only
the non-NAs. If this is what we want to do all the time then we
can omit the
NA from the data set it self in the first
place. This is done by the
hip1 = na.omit(hip)
This function takes a very drastic measure: it simply wipes out
all rows with at least one
NA in it.
Notice how the other means have also changed.
course, you may want to change only the
variable. Then you
B.V1 = na.omit(hip[,"B.V"])
There is another way to ignore the
Compute the variances of all the columns of
NAs without omitting them from
the original data set.
na.rm is an argument that specifies whether
NAs should be removed. By setting it equal
TRUE) we are asking the function to
remove all the obnoxious
You can use this inside
apply as well
Attaching a data set
A data set in R is basically a matrix where each column denotes a
hip data set, for example, has 8
variables (after removing the first column) whose names are obtained as
To access the RA variable we may use
hip[,"RA"] # too much to type
hip[,3] # requires remembering the column number
Fortunately, R allows a third mechanism to access the individual
variables in a data set that is often easier. Here you have to
attach the data set
This unpacks the data set and makes its columns accessible by
name. For example, you can now type
RA # instead of hip[,"RA"]
We can of course still write
Graphical representations of data are a great way to get a
``feel'' about a data set, and R has a plethora of plotting
Consider the two data sets shown along a number line.
When we look at the data sets for the first time our eyes pick up
the following details:
|Two data sets
In other words, our eye notices where the bulk of the data is, and
is also attracted by points that are away from the bulk.
The boxplot is a graphical way to show precisely these
- the blue data set (topmost) has smaller spread than the red one
- the central tendency of blue data set is more to the right
than the red one
- there are some blue points somewhat away from the bulk of the
It requires some knowledge to interpret a boxplot (often called a
box-and-whiskers plot). The following diagram might help.
|Boxplots for the two data sets
Let us use the
|An annotated boxplot
boxplot function on our data set.
Boxplots are usually more informative when more than one
variable are plotted side by side.
The size of the box roughly gives an idea about the spread of the
Boxplots are not supposed to be terribly informative, but
they are often handy for obtaining a rough idea about a data set.
Next let us make a scatterplot.
This produces a scatterplot, where each pair of values is
shown as a point. R allows a lot of control on the appearance of
the plot. See the effect of the following.
main="RA and DE from Hipparcos data")
You may change the colour and point type.
Sometimes it is important to change the colours of some
points. Suppose that we want to colour red all the points with
DE exceeding 0. Then the
function comes handy.
cols = ifelse(DE>0,"red","black")
This means "
cols is red if
it is black".
You may similarly use a vector for
pch so that
different points are shown differently. There are many other
plotting options that you can learn using the online help. We
shall explain some of these during these tutorials as and when
To learn about the different plotting options in R you need to
look up the help of the |
It has a long list of options. Before attempting to make your first
publication-quality graph with R you should better go through
Instead of making all such plots separately for different pairs
of variables we can make a scatterplot matrix
Make a scatterplot of
you see any pattern?
Histograms show how densely or sparsely the values of a variable
lie at different points.
The histogram shows that the maximum concentration of values
occurs from 0.5 to 1. The vertical axis shows the number of
values. A bar of height 600, standing on the range 0.4 to 0.6,
for example, means there are 600
values in that range. Some people, however, want to scale the
vertical axis so that the total area of all the rectangles is 1.
Then the area of each rectangle denotes the probability of its
Sometimes we want more than one plot in a single page (mainly to
facilitate comparison and printing). The way to achieve this in
R is rather
weird. Suppose that we want 4 plots laid out as a 2 by 2 matrix
in a page. Then we need to write
oldpar = par(mfrow=c(2,2))
par function sets graphics options that determines
how subsequent plots should be made.
par function controls the global graphics set up. All
future plots will be affected by this function. Everytime it is
called the old set up is returned by the function. It is a
good idea to save this old set up (as we have in a variable called
oldpar) so that we can restore the old set up later.
means multi-frame row-wise. The vector
c(2,2) tells R to use a 2 by 2 layout. Now let us
make 4 plots. These will be added to the screen row by row.
x = seq(0,1,0.1)
To restore the original ``one plot per page'' set up use
Adding to existing plots
Sometimes we want to add something (line, point etc) to an
existing plot. Then the functions
points are useful.
This adds the line y = a + bx to the plot. Also try
To add curved lines to a plot we use the
x = seq(0,10,0.1)
We can add new points to a plot using the
There are more things that you can add to a plot. See, for
example, the online help for the
Extracting the Hyades stars
Sometimes we have to work with only a subset of the entire
data. We shall illustrate this next by
selecting only the Hyades stars from the data set.
To do this we shall use the facts
that the Main Sequence Hyades stars have
|This are borrowed from Prof Hunter's notes, where he uses astronomy
knowledge to obtain these conditions by making suitable
plots. The interested reader is encouraged to look into his notes
Let us see how we apply these conditions one by one. First, we
RA in the range (50,100)
DE in the range (0,25)
pmRA in the range (90,130)
pmDE in the range (-60,-10)
Vmag >4 OR
B.V <0.2 (this eliminates 4 red giants)
attach the data set so that we may access each
variable by its name.
Next we shall apply the conditions as filters.
filter1 = (RA>50 & RA<100 & DE>0 & DE<25)
filter2 = (pmRA>90 & pmRA<130 & pmDE>-60 & pmDE< -10)
filter3 = filter1 & filter2 & e_Plx<5
HyadFilter = filter3 & (Vmag>4 |B.V <0.2)
& denotes (as expected) logical AND
while the vertical bar
| denotes logical OR.
We are going to need this filter in the later tutorials. So it is
a good idea to save these lines in a script file called, say,
By the way, the filters are all just vectors of
FALSEs. The entry for a star is
TRUE if and
only if it is a Hyades star.
Now we shall apply the filter to the data set. This produces a
new (filtered) data set which we have called
hyades. Finally we
attach this data set.
hyades = hip[HyadFilter,]
You'll see a bunch of warning messages when you
the filtered data set. This is because the old (unfiltered)
variables are now being superceded by the new
(filtered) variables of the same name.
R always issues a warning whenever a variable from a new data set
clashes with some existing variable of the same name. This prevents
the user from accidentally changing a variable. In our case,
however, we did it deliberately. So we can ignore the warning.
All subsequent command will work with only Hyades stars.
We shall often work with the Hyades stars in the later
tutorials. So let us save in a script file hyad.r the commands to
extract the Hyades star.