2. Create a file, with name "car.txt", using any text editor (notepad preferred if on Windows PC). "car.txt" contains the age of a used car and its price gathered from a newspaper, which looks like
Age, Price
6, 6
5, 9
4, 8
3,10
2,11
2,12
1,11
1,13
3. Try the following in the R command window:
tmp<-read.table("car.txt", header=TRUE, sep=","); ## This read file "car.txt" and store it in variable named tmp
x<-tmp[,1]; ## To assign the first column to variable x
y<-tmp[,2]; ## To assign the second column of "car.txt" to variable y
xs<-sort(x, index.return =TRUE);
mylm<-lm(y ~ x);
plot(x,y,xlab="Age", ylab="Price",cex.lab=1.5,cex.axis=1.5, bty="l",pch=20, font.axis=2, font.lab=2);
points(xs$x,fitted(mylm)[xs$ix],type="l",lwd=2);
Alternatively, you can put all the above commands in a file named as "car.R", and then run it from the R command window (consult the R document for help on this).
Comments:
1) This simple program will read data from a file named "car.txt", plots the data (call a scatter plot), and then place a regression line (a line that is `close' to the data points, you will learn this later in the course). This regression line tells, roughly, the overall trend of price for a used car as it ages.
2) From this program, you will learn several things
How to read data from a file
How to access the contents of an array
The plot function and the usage of its parameters
How to draw a line from points
The linear regression function lm() (you will learn this later)
The sort() function