Skip to content

Instantly share code, notes, and snippets.

@dschmeh
Last active January 23, 2018 08:32
Show Gist options
  • Save dschmeh/8414b63c3ab816c44995cd6872165f0e to your computer and use it in GitHub Desktop.
Save dschmeh/8414b63c3ab816c44995cd6872165f0e to your computer and use it in GitHub Desktop.
Function to retrive data from the Google Translation API in R
#' Translate with R
#'
#' Translate Keywords or/and text with the Google Translate API
#' The Functions allows to translate keywords or sentences using the Google Translate API.
#' To use this function you need to get a API-Key for the Google Translate API <https://cloud.google.com/translate/docs/?hl=en>.
#' @param text The keyword/sentence/text you want to translate
#' @param API_Key Your API Key. You get the API Key here: <https://cloud.google.com/translate/docs/?hl=en>
#' @param target The Language target your text translated to. For German 'de'.
#' @param source The Language your given text/keyword is. For example 'en' - english
#' translate()
#' @examples
#' \dontrun{
#' translate(text = "R is cool", API_Key = "XXXXXXXXXXX", target = "de", source = "en")
#' }
translate <- function(text,
API_Key,
target = "de",
source = "en") {
b <- paste0(
'{
"q": [
"',
text,
'"
],
"target": "',
target,
'",
"source": "',
source,
'",
"format": "text"
}'
)
url <-
paste0("https://translation.googleapis.com/language/translate/v2?key=",
API_Key)
x <- httr::POST(url, body = b)
x <- jsonlite::fromJSON(rawToChar(x$content))
x <- x$data$translations
return(x$translatedText[1])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment