【问题标题】:Writing a function for getting data from a URL编写一个从 URL 获取数据的函数
【发布时间】:2020-06-02 08:56:52
【问题描述】:

我正在尝试编写以下函数,用于从 URL 获取 Facebook 数据,然后转换为数据框。

read_URL <- function(df_name,start_date,end_date,token){
  URL <-  fromJSON(paste0("https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until"start_date".since"end_date"&access_token=",token,""))
  df_name <- URL$posts$data
}

不幸的是,我的功能不起作用,我不知道为什么。 显然 URL 在尝试转换为函数之前有效。 这是我得到的错误:

Error: unexpected symbol in:
"read_URL <- function(df_name,start_date,end_date,token){
  URL <-  fromJSON(paste0("https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until"start_date"
>   df_name <- URL$posts$data
Error: object 'URL' not found
> }

任何帮助将不胜感激 错误:“}”中出现意外的“}”

【问题讨论】:

    标签: r function date url


    【解决方案1】:

    我认为您正在尝试使用粘贴来构造 URL。试试看:

    library(jsonlite)
    
    read_URL <- function(df_name,start_date,end_date,token){
       URL <-  fromJSON(paste0('https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until', start_date, ".since", end_date, "&access_token=",token))
       df_name <- URL$posts$data
       return(df_name)
    }
    

    您还可以查看glue 包,它使带参数的 URL 构造变得简单。

    read_URL <- function(df_name,start_date,end_date,token){
        URL <-  fromJSON(glue::glue('https://graph.facebook.com/v5.0/me?fields=posts.limit(30).until{start_date}.since{end_date}&access_token={token}'))
        df_name <- URL$posts$data
        return(df_name)
    }
    

    【讨论】:

    • 感谢 Ronak,如果您知道如何在 for 循环中使用此函数,以便每次迭代将开始日期增加到结束日期 15 天,然后将它们添加到表中跨度>
    • 您应该将此作为一个新问题提出。尝试使用seq 函数创建日期,您可以使用lapply 对其进行迭代。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    相关资源
    最近更新 更多