我从Google Analytics为多个网站和视图提取大量数据,以便在R中进行处理。为了简化流程,我已将最常见的查询添加到某个功能中(所以我只需要传递个人资料ID和日期范围)。每个查询都存储为函数中的局部变量,并分配给动态命名的全局变量:
R version 3.1.1
library(rga)
library(stargazer)
# I would add a dataset, but my data is locked down by client agreements and I don't currently have any test sites configured.
profiles <- ga$getProfiles()
website1 <- profiles[1,]
start <- "2013-01-01"
end <- "2013-12-31"
# profiles are objects containing all the ID's, accounts #, etc.; start and end specify date range as strings (e.g. "2014-01-01")
reporting <- function(profile, start, end){
id <- profile[,1] #sets profile number from profile object
#rga function for building and submitting query to API
general <- ga$getData(id,
start.date = start,
end.date = end,
metrics = "ga:sessions")
... #additional queries, structured similarly to example above(e.g. countries, cities, etc.)
#transforms name of profile object to string
profileName <- deparse(substitute(profile))
#appends "Data" to profile object name
temp <- paste(profileName, "Data", sep="")
#stores query results as list
temp2 <- list(general,countries,cities,devices,sources,keywords,pages,events)
#assigns list of query results and stores it globally
assign(temp, temp2, envir=.GlobalEnv)
}
#call reporting function at head of report or relevant section
reporting(website1,start,end)
#returns list of data frames returned by the ga$getData(...), but within the list they are named "data.frame" instead of their original query name.
#generate simple summary table with stargazer package for display within the report
stargazer(website1[1])
我可以通过*website1*Data[1]
访问这些结果,但我将数据交给合作者。理想情况下,他们应该能够按名称访问数据(例如*website1*Data$countries
)。
是否有更简单/更好的方式来存储这些结果,并且可以在.Rmd报告中更轻松地访问它们?
答案 0 :(得分:0)
没有真正的理由在函数旁边执行deparse只是为了在父环境中分配变量。如果必须调用reporting()
函数,只需让该函数返回一个值并分配结果
reporting <- function(profile, start, end){
#... all the other code
#return results
list(general=general,countries=countries,cities=cities,
devices=devices,sources=sources,keywords=keywords,
pages=pages,events=events)
}
#store results
websiteResults <- reporting(website1,start,end)