2

我想每小时通过包“gtrendsR”提取谷歌趋势数据,我尝试使用 Sys.sleep() 函数设置计时器,但是每小时下载一次对我来说是失败的。那么,我如何更正我的代码以便每小时获取数据。非常感谢!

Sys.setlocale("LC_ALL", "English")
Keywords = c("google", "twitter")

for (k in Keywords) {
  res = NULL

  temp_1 <- gtrends(k, geo = "US",time = "all")
  temp_2 <- temp_1$interest_over_time
  res <- rbind(res, temp_2)
  rm(temp_1,temp_2)

  res <- select (res, c(date, hits))

  Sys.setlocale(category = "LC_ALL", locale = "cht")
  names(res)[2]<- k
  xfilepath = paste("C:/Users/Peter/Desktop/",k,".csv",sep="")
  write.csv(res, file = xfilepath, row.names=FALSE)

}
4

1 回答 1

1

Sys.sleep()应该可以工作,如果没有错误代码,很难准确地告诉您它失败的原因。不过,我会建议另一种方法。

later包是一个简单而漂亮的实用程序包,用于执行代码,嗯..稍后。它接受一个没有任何参数的函数,并以设定的延迟运行它。例如,您可以使用:

library("gtrendsR")
library("later")
library("data.table") #for as.ITime
Sys.setlocale("LC_ALL", "English")
Keywords = c("google", "twitter")
#Set delay. Here for 5 seconds
delay <- as.ITime("00:00:05")
Interrupt <- FALSE

extractGoogle <- function(){
    for (k in Keywords) {
        res = NULL
        temp_1 <- gtrends(k, geo = "US",time = "all")
        temp_2 <- temp_1$interest_over_time
        res <- rbind(res, temp_2)
        rm(temp_1,temp_2)
        res <- select (res, c(date, hits))
        Sys.setlocale(category = "LC_ALL", locale = "cht")
        names(res)[2]<- k
        xfilepath = paste("C:/Users/Peter/Desktop/",k,".csv",sep="")
        write.csv(res, file = xfilepath, row.names=FALSE)
    }
    #Execute once again later
    if(isFALSE(Interrupt))
        later(extractGoogle, delay = delay)
}
#Run the function until Interrupt is set to TRUE or session closes
extractGoogle()

这允许您手动设置延迟,将“延迟”更改为秒数。as.ITimesimple 允许您以简单格式指定秒数。然后可以通过更改全局变量进一步延迟或中断循环。

于 2019-06-22T08:39:28.590 回答