R script to import data from google analytics

♀尐吖头ヾ 提交于 2019-12-19 03:54:49

问题


I am trying to connect to google analytic s API through a script running on R studio server.

I have followed steps from this tutorial:

http://www.r-bloggers.com/how-to-extract-google-analytics-data-in-r-using-rgoogleanalytics/

If I run this on localhost, it works alright but when I try to run the script on a remote server through R studio,

authroization step does not complete because it tries to connect to the url on localhost i.e

localhost:1410/

instead of REMOTESERVERHOSTNAME:1410

I found this post which suggests port forwarding if running through R studio : link

but if tomorrow, if I want to access it on the other host computer, I would not want to set port forwarding first.

How to run this script without having to set port forwarding?What are other ways for oauth authentication for my R script?


回答1:


One suggestion would be to use a Google Service Account. The googleAuthR package by Mark Edmondson, available through CRAN, provides functionality to perform server-side authentication in R using a Google Service Account. Another package by the same author called googleAnalyticsR, also on CRAN, integrates with googleAuthR and uses the resulting authentication token to execute queries against the Google Analytics Reporting APIs, including the latest version, 4.0.

To achieve this:

  1. Create a service account for your Google API project.
  2. Download the JSON file containing the private key of the service account.
  3. Grant the service account access to Google Analytics, in the same way as you would for any other user.
  4. Supply the location of the private key JSON file as an argument when authenticating with googleAuthR (see the example below.):

The following example R script references the JSON file containing the private key and performs a basic Google Analytics reporting query. Remember to set the json_file argument to the appropriate file path and the id argument to the appropriate Google Analytics view:

library(googleAuthR)
library(googleAnalyticsR)

gar_auth_service(
  json_file = "API Project-xxxxxxxxxxxx.json",
  scope = "https://www.googleapis.com/auth/analytics"
)

google_analytics(id = "123456789", start = "2016-06-01", end = "2016-06-28")


来源:https://stackoverflow.com/questions/37525910/r-script-to-import-data-from-google-analytics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!