Accessing FitBit data in R

I caught a pretty amazing episode of Horizon (the BBC’s in depth science program in the UK) a while back called “The future of medicine is apps“. The programme explored the health benefits of giving people data about their body, health and lifestyle. The more extreme examples included the tracking of the England rugby team during training which allows the coaches to predict injury/flu before the player’s are aware of it, and the professor that monitored the level of every metabolite in his blood every day and was able to diagnose himself with Chron’s disease prior to any symptoms. At the more practical level were the people who simply track their activity levels each day. The theory goes that if you are aware via a direct data feed of what you are doing (or not doing I suppose) then you are able to make changes to your lifestyle for the better. Being a just a bit of a geek I was inspired to get myself an activity tracker and see what it was to collect some data on myself.

I settled on a FitBit Flex, which is essentially a pedometer that you wear on your wrist and which tracks activity (steps) as well as sleep patterns. I have to say it works really well and I am mightily addicted to trying to meet my activity goal each day – currently set to the default of 10,000 steps. FitBit provide a fairly slick website to display all the data you collect but, unfortunately, if you want to download the data and do any kind of analysis yourself you have to pay a pretty exorbitant subscription fee. Luckily, you can get at your data via their API if you have the know-how so I decided have a go in R.

First off you have to register an “app” with FitBit (mine is called StepTrack!) in order to get the credentials needed for authentication. I used the httr package for the OAuth authentication and data retrieval.

library(httr)

token_url = "http://api.fitbit.com/oauth/request_token"
access_url = "http://api.fitbit.com/oauth/access_token"
auth_url = "http://www.fitbit.com/oauth/authorize"
key = "my_key"
secret = "my_secret"

fbr = oauth_app('StepTrack',key,secret)
fitbit = oauth_endpoint(token_url,auth_url,access_url)
token = oauth1.0_token(fitbit,fbr)
sig = sign_oauth1.0(fbr, token=token$oauth_token, token_secret=token$oauth_token_secret)

# get all step data from my first day of use to the current date:
steps = GET("http://api.fitbit.com/1/user/-/activities/steps/date/2013-08-24/today.json",sig)

The data is returned as json, which can then be plotted to your hearts content. In the plot you can see a five day gap – I went on holiday and forgot the charger!

> steps
Response [http://api.fitbit.com/1/user/-/activities/steps/date/2013-08-24/today.json]
Status: 200
Content-type: application/json;charset=UTF-8
{"activities-steps":[{"dateTime":"2013-08-24","value":"5455"},{"dateTime":"2013-08-25","value":"11822"},{"dateTime":"2013-08-26","value":"11692"},{"dateTime":"2013-08-27","value":"17028"},{"dateTime":"2013-08-28","value":"10225"},{"dateTime":"2013-08-29","value":"8632"},{"dateTime":"2013-08-30","value":"9920"},{"dateTime":"2013-08-31","value":"9321"},{"dateTime":"2013-09-01","value":"13581"},{"dateTime":"2013-09-02","value":"7465"},{"dateTime":"2013-09-03","value":"0"},{"dateTime":"2013-09-04","value":"0"},{"dateTime":"2013-09-05","value":"0"},{"dateTime":"2013-09-06","value":"0"},{"dateTime":"2013-09-07","value":"335"},{"dateTime":"2013-09-08","value":"9239"},{"dateTime":"2013-09-09","value":"17059"}]}

step_plot

Admittedly I am struggling to come up with ideas of what to do with the data that FitBit doesn’t provide already through their website. But, its the principal of the thing – I should be able to get at my data and now I can. For all of the data shown in the above I was on holiday and in general much more active than when i’m plonked in my desk at work. It will be interesting to see what my daily step count is on a normal working day and whether knowing this will push me on to go for a run at lunch time or take the very long route to the sandwich shop. Being a very competitive person, I suspect it will.

UPDATE: 4th April 2014 – @asrowe has made a nice comparison of two trackers (fitbit and jawbone) here.

About these ads

10 thoughts on “Accessing FitBit data in R

    • Something like this:

      library(RColorBrewer)
      library(rjson)

      # convert JSON to a dataframe:
      data = NULL
      for (i in 1:length(content(steps)$`activities-steps`)) {
      x = c(content(steps)$`activities-steps`[i][[1]]$dateTime,content(steps)$`activities-steps`[i][[1]]$value)
      data = cbind(data,x)
      }
      data = t(data)
      colnames(data) = c("date","steps")
      data = as.data.frame(data,row.names=1)

      # extract step counts and convert to numeric:
      steps = as.numeric(as.character(data$steps))

      # set up and plot the graph:
      brew = brewer.pal(3,"Set1") # red, blue, green
      cols = rep(brew[1],length(steps))
      cols[steps > 10000] = brew[3]
      barplot(steps,ylim=c(0,max(steps)*1.2),col=cols,ylab="Steps",names=gsub("2013-","",data$date),las=2,border=0,cex.axis=0.8)
      abline(h=10000,lty=2)

  1. Thanks for the code! I have a problem in the following line:
    token = oauth1.0_token(fitbit,fbr)

    After executing this command, the console prints the following: “Waiting for authentication in browser…” And a new browser window opens to ask me for permission. When I accept it, then I got a PIN code, and I do not know how to proceed. I am not sure if it may be a problem with the configuration of my APP. Because of my missunderstanding of the oauth protocol, I don’t know what things should I check. Any advise would be more than wellcome!

    • Ok, I resolved this issue by myself. The problem is that I configured the application as desktop and not as web app. Now, I get the authentication complete.

  2. Pingback: 2013 with Fitbits | Jean-Etienne's blog

  3. The httr library has recently been updated and one of the methods is now deprecated. I made the following updates to make it work

    The lines:
    token = oauth1.0_token(fitbit,fbr)
    sig = sign_oauth1.0(fbr, token=token$oauth_token, token_secret=token$oauth_token_secret)

    Should be replaced with:
    token = oauth1.0_token(fitbit,fbr)
    sig <-config(token = token)

  4. Pingback: Analysing squash performance using fitbit data | Bioinpharmatics

  5. Pingback: What We Are Reading | Quantified SelfQuantified Self

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s