r-使用RGoogleAnalytics从谷歌检索数据



我使用RGoogleAnalytics来检索多个维度的数据,但每次我尝试运行ga.data <- ga$GetReportData(query)然后我得到一条错误消息:fromJSON中的错误(api.response.json,method="C"):位置53处出现意外的转义字符"\"我尝试其他功能时没问题我该怎么解决这个问题我使用以下代码:

require("RGoogleAnalytics")
query <- QueryBuilder()
access_token <- query$authorize()                                                
ga <- RGoogleAnalytics()
ga.profiles <- ga$GetProfileData(access_token)
profile <- ga.profiles$id[3] 
startdate <- "2013-10-01"
enddate <- "2013-12-31"
dimension <- "ga:date,ga:source,ga:medium,ga:keyword,ga:city,ga:operatingSystem,ga:landingPagePath"
metric <- "ga:visits,ga:goal1Completions,ga:goal3Completions"
sort <- "ga:visits"
maxresults <- 500000
query$Init(start.date = startdate,
end.date = enddate,
dimensions = dimension,
metrics = metric,
max.results = maxresults,
table.id = paste("ga:",profile,sep="",collapse=","),
access_token=access_token)
ga.data <- ga$GetReportData(query)

我也遇到了一些麻烦,找到了一种方法。

步骤1:安装程序包

# lubridate
install.packages("lubridate")
# httr 
install.packages("httr")
#RGoogleAnalytics

使用此链接下载此特定版本的RGoogleAnalyticshttp://cran.r-project.org/web/packages/RGoogleAnalytics/index.html

步骤2:创建客户端ID和机密ID

  1. 导航到谷歌开发者控制台。(https://console.developers.google.com/project)
  2. 创建一个新项目并打开它
  3. 导航到API并确保为您的项目打开了Analytics API
  4. 导航到凭据并创建新客户端ID
  5. 选择应用程序类型–已安装的应用程序
  6. 创建客户端ID和客户端机密后,将它们复制到R脚本中。

    client.id <- "xxxxxxxxxxxxxxxxxxxxxxxxx"
    client.secret <- "xxxxxxxxxxxxxxx"
    token <- Auth(client.id,client.secret)
    

    为将来的会话保存令牌对象

    save(token,file="./token_file")
    

在未来的会话中,您不需要每次都生成访问令牌。假设您已将其保存到文件中,它可以通过以下代码段加载-

load("./token_file")

验证和刷新令牌

ValidateToken(token)

步骤3:构建所需查询

query.list <- Init( start.date = "2014-08-01",
end.date = "2014-09-01",
dimensions = "ga:sourceMedium",
metrics = "ga:sessions,ga:transactions",
max.results = 10000,
sort = "-ga:transactions",
table.id = "ga:0000000")

创建查询生成器对象,以便验证查询参数

ga.query <- QueryBuilder(query.list)

提取数据并将其存储在数据帧中

ga.data <- GetReportData(ga.query, token,paginate_query = FALSE)

便捷链接

常见错误:开发者。google.com/analytics/devguides/reporting/core/v3/coreErrors#standard_Errors

查询资源管理器:ga-dev-tools.appspot.com/Query-Explorer/?csw=1

维度和指标:developers.google.com/analystics/devguides/reporting/core/dimsmets

当Rjson库无法正确解析Google Analytics JSON Feed时,似乎会出现此错误。请试用CRAN最近发布和更新的RGoogleAnalytics库版本。

最新更新