Analysis of sensor data using R


As discussed before, data of the sensors attached to my RasPi are stored in a MySQL database. I wrote some bash scripts to produce graphs using GNUplot which are presented as a gallery. After collecting data for a couple of weeks, I wanted to apply some statistics on the data to obtain a quick overview, i.e. to produce a whiskers or boxplot. Therefore, I decided to use R for this purpose.

feb14Data retrieval from MySQL database

My RasPi is running headless. In order to work with the data on an other machine it is necessary to export the desired subset from the database. Unfortunately, the INTO OUTFILE statement of MySQL doesn’t allow to choose a remote server for saving a CSV file. Therefore, one has to redirect the SQL output into a file. For replacing the tabstops with a different separator, one can pipe the SQL output through sed:

mysql -h servername -u username --password=secret -e "SELECT * FROM table where FROM_UNIXTIME(timestamp) >=NOW() - INTERVAL 7 DAY;" | sed 's/\t/;/g;s/\n//g' > week.csv

As a result a CSV file is generated containing a subset of observations from last 7 days.


Remember that a header is included in the first row, containing the field names. In R, the CSV file can be imported as a dataframe, with:

dataframe <- read.csv("filename", sep=";", header=T, stringsAsFactors=F)

If your table doesn’t contain a header, set header=F and use the names() command to rename V1, V2, V3 …

 names(dataframe) <- c("date","time","ts","temp1","hum1","temp2","bar","alt","lux","temp3")

Although one can create plots using the timestamp for the X-axis, I prefer a more human-readable format. Therefore, I convert the timestamp into ISO format:

dataframe$ts <- ISOdatetime(1970,1,1,0,0,0,tz="CET")+dataframe$ts

Instead of using a temporal CSV file, it is also possible to import data directly into R. This requires the RMySQL package, which can be installed with: