In your working folder there will be a file called ukgas.csv. UKgas is a dataset of the quarterly UK gas consumption from 1960 Q1 to 1986 Q4, in millions of therms. It is native to R as a built in dataset but we will learn how to read a file in. |
UKgas is a dataset of the quarterly UK gas consumption from 1960 Q1 to 1986 Q4, in millions of therms. It is native to R as a built in dataset but we will learn how to read a file in.
|
Remember to comment your code e.g. #this is a comment or even create code sections e.g. ################################### |
read.csv
function in the help file to learn how to read a .csv data file into R (web manual page).?read.csv |
file1<-read.csv("ukgas.csv") |
file1
variable in your top right Environment windowfile1 # this displays all data in file1 head(file1) # this displays xxxxxxxxx tail(file1) # this displays xxxxxxxxxxxxx file1 [1,] # this displays xxxxxxxxxxx file1[1:5,] # displays xxxxxxxxxxx file1[,1] # this displays xxxxxxxxxxxxxxxxxx file1[,1:5] # this displays xxxxxxxxxxxx file1[,'year'] # this displays xxxxxx file1 [,'qtr1'] # this displays xxxxxx |
You can
It is best practice to use |
plot
function:?plot |
plot(x = year, y = qtr1) |
type
argument to change the plot to linespar
function - this allows you to set additional parameters in graphs. In the manual page search (using Ctrl F) for the word color.
Find and implement the argument for plotting colour - make your plotting colour ‘red’.?png png(file="plot1.png") # opens the png printing driver, output to appear in plot1.png plot(x = year, y = qtr1, type = 'b', col = 'red') # this plot is printed dev.off() #prin driver closed |
A pdf output can be printed using:
|
R plots in layers. You start with a base plot using the plot
function and then can add layers of extra data, regression lines, legends, text equations etc on top of it using:
points
to learn how to add additional data to a plot. points
to add qtr2 data points to the qtr1 graph. Remember you will need to assign your qtr2 data to a new variable before you can plot it. #look up points in help file ?points #assign qtr2 data to variable called qtr2 qtr2 = file1[,'qtr2'] #plot qtr 1 plot(x = year, y = qtr1, type = 'l', col = 'red') #add qtr2 data points(x = year, y = qtr2, type = 'l', col = 'black') |
The arguments that can be applied in the |
legend
function. Use the information to add a legend to the plot.#look up points in help file ?legend #assign qtr2 data to variable called qtr2 qtr2 = file1[,'qtr2'] #plot qtr 1 plot(x = year, y = qtr1, type = 'l', col = 'red') #add qtr2 data points(x = year, y = qtr2, type = 'l', col = 'black') #add legend legend(x = 'topleft', y = NULL, legend = c('qtr1', 'qtr2'), col = c('red', 'black'), lty = 1) |
You will see that qtr 3 plots data off the y axis. Use the
|
You have now completed Exploring the data: the basics. Make sure you:
|