我正在查询来自GA的数据,其中每个迭代的开始日期都包含在列表中(begDate)。我已经研究过如果在lapply循环遍历列表之前发生错误,如何使用tryCatch来停止丢失查询数据。 通常,错误是由于超时而发生的。我希望能够在移动到下一个元素之前重试该元素。为此,我在错误处理程序中输入了与tryCatch主体相同的代码。但是,当错误处理程序中的查询超时时,这也不好。我该怎么写得好呢?我发现的大多数帖子都是在循环中处理这个问题,或者转到下一个元素。我也看过了里斯特,但是不明白如何使用它。
begDate<-array(c(seq(as.Date("2014-04-01"), as.Date("2014-04-03"), by="1 day"))) #defining start date for each query
Test<-lapply(begDate, function(bDt){ #uses each element of begDate as the beginning time period of query with 90 day length
rg2<-paste0("users::condition::ga:sessionCount==1;dateOfSession<>", as.Date(bDt, origin = "1970-01-01"), "_", as.Date(bDt, origin = "1970-01-01"), ";users::condition::ga:goalCompletionsAll>0" )
tryCatch( ga$getData(id,
walk = TRUE,
batch = TRUE,
start.date = as.Date(bDt+1, origin = "1970-01-01"),
end.date = as.Date(bDt+15, origin = "1970-01-01"),
metrics = "ga:sessions, ga:goalCompletionsAll" ,
dimensions = "ga:date, ga:goalPreviousStep1, ga:goalPreviousStep2, ga:goalPreviousStep3",
segment = paste0(rg2),
filters = ""
)
, error=function(e) { # just retries the query
ga$getData(id,
walk = TRUE,
batch = TRUE,
start.date = as.Date(bDt+1, origin = "1970-01-01"),
end.date = as.Date(bDt+15, origin = "1970-01-01"),
metrics = "ga:sessions, ga:goalCompletionsAll" ,
dimensions = "ga:date, ga:goalPreviousStep1, ga:goalPreviousStep2, ga:goalPreviousStep3",
segment = paste0(rg2),
filters = ""
)
}
)
})
答案 0 :(得分:0)
这是我发现在没有知道如何编写更好代码的情况下最稳定的解决方案(我一直在努力改进)。
Test<-lapply(begDate, function(bDt){ #uses each element of begDate as the beginning time period of query with 50 day length
rg2<-paste0("users::condition::ga:source=~", urlV, ";dateOfSession<>", as.Date(bDt, origin = "1970-01-01"), "_", as.Date(bDt, origin = "1970-01-01") )
tryCatch(ga $ getData(id, walk = TRUE, batch = TRUE, start.date = as.Date(bDt + 1,origin =“1970-01-01”), end.date = as.Date(bDt + 50,origin =“1970-01-01”), metrics = paste0(metr), dimensions = paste0(昏暗), segment = seg, filters =“ga:country = ~United States” )
,error = function(e){ Sys.sleep(7) tryCatch(ga $ getData(id, walk = TRUE, batch = TRUE, start.date = as.Date(bDt + 1,origin =“1970-01-01”), end.date = as.Date(bDt + 50,origin =“1970-01-01”), metrics = paste0(metr), dimensions = paste0(昏暗), segment = seg, filters =“ga:country = ~United States” ) ,error = function(e)print(paste0(bDt,“”,e))) })
})