申请里面的申请功能?

时间:2020-02-27 03:14:42

标签: r apply google-analytics-api

我有一个数据框,其中包含2019年每个月的开始和结束时间。

我需要提取一个API,编写一个名称为mydf加上月份(例如mydf-01.csvmydf-02.csv等)的CSV文件。

我需要获取数据,写入CSV,清理内存以避免错误消息“内存不足”,然后继续下个月。

现在我有了这个,但给我一个错误:内存不足,因为整个2019年的预期数据约为3GB。

我正在考虑进行for循环。但是也许我可以使用另一个Apply系列功能?

月:my_dates data.frame

外观如下:

from        to
2019-01-01  2019-01-31
2019-02-01  2019-02-28
2019-03-01  2019-03-31
...

生成12个月的代码:

som <- function(x) as.Date(cut(as.Date(x), "month")) # start of month
eom <- function(x) som(som(x) + 32) - 1 # end of month

month_ranges <- function(from, to) {
  s <- seq(som(from), as.Date(to), "month")
  data.frame(from = pmax(as.Date(from), s), to = pmin(as.Date(to), eom(s)))
}

my_dates <- month_ranges(som("2019-01-01"), eom("2019-12-31"))

获取数据的代码:

当前,它将获取所有月份,并将其保存在内存中,最后 它将它们捆绑在一起。但是,这种方法在以下情况下会出错 月份范围太大,因为数据超过2GB。因此,我希望每个月将数据保存到CSV并继续到下个月。

library(googleAuthR)
library(googleAnalyticsR)

my_fetch <- function(ga_id, d1, d2) {
  google_analytics(ga_id,
                   date_range = c(d1, d2),
                   metrics = c("totalEvents"),
                   dimensions = c("ga:date", "ga:eventCategory", "ga:eventAction", "ga:eventLabel"),
                   anti_sample = TRUE,
                   anti_sample_batches = 1,
                   rows_per_call = 400)
}


my_fetches_fetches <- mapply(my_fetch, myviewID, my_dates$from, my_dates$to, SIMPLIFY = FALSE)


total <- do.call(rbind, my_fetches_fetches)

更新1:

也许可以传递产生错误的“循环”,例如API超时继续到下个月?

0 个答案:

没有答案
相关问题