Skip to content

Instantly share code, notes, and snippets.

@stephlocke
Created June 13, 2017 10:24
Show Gist options
  • Save stephlocke/441ea493be926b76bac59452a3f57281 to your computer and use it in GitHub Desktop.
Save stephlocke/441ea493be926b76bac59452a3f57281 to your computer and use it in GitHub Desktop.
Call Microsoft Cognitive Services APIs in R
library(httr)
library(jsonlite)
library(dplyr)
library(purrr)
cogapikey<-"XXX"
text=c("is this english?"
,"tak er der mere kage"
,"merci beaucoup"
,"guten morgen"
,"bonjour"
,"merde"
,"That's terrible"
,"R is awesome")
# Put data in an object that converts to the expected schema for the API
data_frame(text) %>%
mutate(id=row_number()) ->
textdf
textdf %>%
list(documents=.) ->
mydata
cogapi<-"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages?numberOfLanguagesToDetect=1"
cogapi %>%
POST(add_headers(`Ocp-Apim-Subscription-Key`=cogapikey),
body=toJSON(mydata)) ->
response
# Process response
response %>%
content() %>%
flatten_df() %>%
select(detectedLanguages) %>%
flatten_df()->
respframe
textdf %>%
mutate(language= respframe$iso6391Name) ->
textdf
# New info
mydata<-list(documents = textdf)
# New endpoint
cogapi<-"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment"
# Construct a request
cogapi %>%
POST(add_headers(`Ocp-Apim-Subscription-Key`=cogapikey),
body=toJSON(mydata)) ->
response
# Process response
response %>%
content() %>%
flatten_df() %>%
mutate(id=as.numeric(id))->
respframe
# Combine
textdf %>%
left_join(respframe) ->
textdf
knitr::kable(textdf)
Copy link

ghost commented Jun 27, 2017

Process response

response %>%

  • content() %>%
  • flatten_df() %>%
  • select(detectedLanguages) %>%
  • flatten_df() ->
  • respframe

Error in overscope_eval_next(overscope, expr) :
object 'detectedLanguages' not found

textdf %>%

  • mutate(language= respframe$iso6391Name) ->
  • textdf

Error in mutate_impl(.data, dots) :
Evaluation error: object 'respframe' not found.

Sorry, your code not run at this point

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment