Drawing a simple line graph with 2 lines : R Programming


In our last post we read in the historical share information about a company, in this post I want to plot the daily share volume amounts against a line indicating the average volume.


> df <- read.csv(‘tesco.txt’)
> str(df)  #look at the structure of the dataframe

If you look at the data type of X.date you will see it is an int. We want to convert this to a proper datetime. I had a few issues with this, and it seems to be as it has been read in as an int when you try to convert it, it thinks it is a milliseconds value. I got around this by first converting the int to a char

> df$X.date = as.Date(as.character(df$X.date), “%Y%m%d”) #convert to date
> df$X.Avg <- mean(df$X.vol.) #create a new column and store the average volume
> plot(df$X.date,df$X.vol, type=”l”) #draw a line graph, l is for line
> lines(df$X.date,df$X.Avg, col=”red”)


It would be nice to get the axis names sorted out, and the formatting of the numbers.



Reading text files and getting a column’s average value : R Programming


Before doing anything interesting in R, we need to have some data to play with. I want to read in a list of End of Day prices for a company, and working out the average volume of that share traded.

This solution is going to require an account on www.eoddata.com to get access to the historical close prices of a share.


I’ve downloaded the close prices for Tesco and placed them in /users/nick/rdata
This is the code to read in the text file and calculate the average volume of shares traded:

> setwd(‘/users/nick/rdata’)  # set the working directory
> df <- read.csv(‘tesco.txt’)
> mean(df$X.vol)
[1] 22283443


Learning R Programming : The Tutorials

I’ve been trying to learn the programming language R for a couple of months now, and while following the course datacamp.com has been good – it is only by doing real (useful) tasks that I feel I can move my knowledge forward enough to be ready to tackle some machine learning competitions on Kaggle.

Back in the day, when transitioning over from VB6 to VB.net, a really useful book that helped me along was Karl Moores Visual Basic.Net : The Tutorials (I even wrote an Amazon review for it – it really must have been good!!!)

My plan is to develop something like this as a set of blog posts, where each posts outlines a problem – with the solution after. I have no doubt that some of the solutions will be suboptimal – but that’s where I hope the interweb will come in handy and help me improve my knowledge.

Lets see how it goes. Here are the topics covered to far.

Reading in a text file and getting the average of a column

Drawing a simple line graph with 2 lines