MxBlog

Using an oData resource in R

The following is a quick example how you can use an oData resource in R:

#
# Test odata
#
library('httr')
library('XML')
library('dplyr') 
#
# basic authentication credentials
#
secret <- RCurl::base64(paste('username', 'password', sep = ":"));
#
# function to retrieve resource and return data.frame containing data
# Assumes simple 1 dimensional resource, no nested resources
#
getOdataResource <- function(url,auth){
response <- GET(url,config(httpheader = c("Authorization" = paste("Basic",auth))))
  responseContent <- content(response,type="text/xml")
  xmlNames <- xpathSApply(responseContent,'//m:properties[1]/d:*',xmlName)
  properties <- xpathSApply(responseContent,'//m:properties/d:*',xmlValue)
  propertiesDF <- as.data.frame(matrix(properties,ncol=length(xmlNames),byrow=TRUE))
  names(propertiesDF) <- xmlNames
  return(propertiesDF)
}
#
# get products odata resource
# 
products <- getOdataResource("http://localhost:8080/odata/Orders/Products",secret)
products$Price <- as.numeric(products$Price)
products$id <- as.numeric(products$id)
#
# create price bins, count number of products in pricebin 
#
products %>%
  mutate(priceBin=round(25*trunc(Price/25))) %>%
  select(Price,priceBin) %>%
  group_by(priceBin) %>%
  summarise(priceBinCount = length(priceBin))