我可以使用R成功地从Localytics查询数据,例如以下示例:
r <- POST(url = "https://api.localytics.com/v1/query,
body=list(app_id=<APP_ID>,
metrics=c("occurrences","users"),
dimensions=c('a:URI'),
conditions=list(day = c("between", "2020-02-11", "2020-03-12"),
event_name = "Content Viewed",
"a:Item URI" = "testing")
),
encode="json",
authenticate(Key,Secret),
accept("application/json"),
content_type("application/json"))
stop_for_status(r)
但是我想做的就是创建一个函数,这样我可以快速执行此操作,而不必复制/粘贴数据。
我遇到的问题是第"a:Item URI" = "testing"
行,我在其中通过所有都等于"testing"
的Item URI过滤所有搜索,但是有时候,我不想包含filter语句,所以我只需完全删除该行即可。
当我编写函数时,我尝试了如下操作:
get_localytics <- function(appID, metrics, dimensions, from = Sys.Date()-30,
to = Sys.Date(), eventName = "Content Viewed",
Key, Secret, filterDim = NULL, filterCriteria = NULL){
r <- httr::POST(url = "https://api.localytics.com/v1/query",
body = list(app_id = appID,
metrics = metrics,
dimensions = dimensions,
conditions = list(day = c("between", as.character(from), as.character(to)),
event_name = eventName,
filterDim = filterCriteria)
),
encode="json",
authenticate(Key, Secret),
accept("application/json"),
content_type("application/json"))
stop_for_status(r)
result <- paste(rawToChar(r$content),collapse = "")
document <- fromJSON(result)
df <- document$results
return(df)
}
但是我尝试将filterDim
和filterCriteria
相加只会产生错误Unprocessable Entity
。 (请记住,我可以过滤很多变量,而不仅仅是"a:Item URI"
,因此我也需要能够操纵它。
我如何添加一条语句,如果需要过滤,可以合并该行,但是如果不需要过滤,则不包括该行?
conditions
只是一个列表,因此您可以有条件地向其中添加元素。在这里,我们只使用if
语句来测试传递的值,如果是,则将它们添加进来。
get_localytics <- function(appID, metrics, dimensions, from = Sys.Date()-30,
to = Sys.Date(), eventName = "Content Viewed",
Key, Secret, filterDim = NULL, filterCriteria = NULL){
conditions <- list(day = c("between", as.character(from), as.character(to)),
event_name = eventName)
if (!is.null(filterDim) & !is.null(filterCriteria)) {
conditions[[filterDim]] <- filterCriteria)
}
r <- httr::POST(url = "https://api.localytics.com/v1/query",
body = list(app_id = appID,
metrics = metrics,
dimensions = dimensions,
conditions = conditions),
encode="json",
authenticate(Key, Secret),
accept("application/json"),
content_type("application/json"))
stop_for_status(r)
result <- paste(rawToChar(r$content),collapse = "")
document <- fromJSON(result)
df <- document$results
return(df)
}