The Art of R Programming

(WallPaper) #1
Theplot()function is another generic function. You can useplot()on
just about any R object. R will find an appropriate plotting function based
on the object’s class.
Classes are used to organize objects. Together with generic functions,
they allow flexible code to be developed for handling a variety of different
but related tasks. Chapter 9 covers classes in depth.

1.5 Extended Example: Regression Analysis of Exam Grades.......................


For our next example, we’ll walk through a brief statistical regression analysis.
There isn’t much actual programming in this example, but it illustrates how
some of the data types we just discussed are used, including R’s S3 objects.
Also, it will serve as the basis for several of our programming examples in
subsequent chapters.
I have a file,ExamsQuiz.txt, containing grades from a class I taught. Here
are its first few lines:

2 3.3 4
3.3 2 3.7
4 4.3 4
2.3 0 3.3


The numbers correspond to letter grades on a four-point scale; 3.3 is a
B+, for instance. Each line contains the data for one student, consisting of
the midterm examination grade, final examination grade, and average quiz
grade. It might be interesting to see how well the midterm and quiz grades
predict the student’s grade on the final examination.
Let’s first read in the data file:

> examsquiz <- read.table("ExamsQuiz.txt",header=FALSE)

Our file does not include a header line naming the variables in each
student record, so we specifiedheader=FALSEin the function call. This is an
example of a default argument, which we talked about earlier. Actually, the
default value of theheaderargument isFALSEalready (which you can check by
consulting R’s online help forread.table()), so we didn’t need to specify this
setting, but it’s clearer if we do.
Our data is now inexamsquiz, which is an R object of classdata.frame.

> class(examsquiz)
[1] "data.frame"

Just to check that the file was read in correctly, let’s take a look at the
first few rows:

> head(examsquiz)
V1 V2 V3

16 Chapter 1

Free download pdf