【问题标题】:R: parse python dictionary over json into xtsR:将json上的python字典解析为xts
【发布时间】:2021-06-03 05:33:33
【问题描述】:

我创建了一些 xts 对象,将它们保存为 csv 文件,将它们上传到谷歌云平台,...,创建 Python 字典,下载字典并获取结果(通过 REST API 一次同时获取多个原始文件)在 R 中使用 Rcurl。

我想再次创建原始 xts 对象,但无法正确解析最终结果。

这是数据流:

其中一个 csv 文件如下所示(它们都具有相同的结构):

R 中的结果是:

library(RCurl)
all_files <- getURL("https://....")
all_parsed <- jsonlite::fromJSON(all_files)

, 是一个列表,看起来像:

如果我用 cat(all_parsed$2020-09-24.csv) 打印结果,它的结构正好适合 xts:

但我不能真正使用这些数据,因为所有的 \n \" 等等

我可以用 strsplit(...) 尝试它,但工作量很大。

有没有更好的方法来解析结果?

抱歉,我无法提供更好的解释/可重现的代码 - 我可以通过邮件将 Rcurl 的 URL 发送给你们中的一些人。

谢谢!

【问题讨论】:

    标签: python r json xts


    【解决方案1】:

    像这样?

    library(stringr)
    
    # Example string
    ex_str <- "\"Index\",\"E2202\"\n\"2020-09-04\",NA\n\"2020-12-02\",2.7"
    
    # First, split on the \n which represents a new line 
    ex_str <- str_split(ex_str, "\n")[[1]]
    
    # Then, drop quotation marks
    str_replace_all(ex_str, "\"", "")
    
    [1] "Index,E2202"    "2020-09-04,NA"  "2020-12-02,2.7"
    

    【讨论】:

      【解决方案2】:

      是的,谢谢。我将完成您的代码:

      eex_str <- str_replace_all(ex_str, "\"", "")[-length(str_replace_all(ex_str, "\"", ""))]
      index_string <- unlist(str_split(eex_str, ","))[c(TRUE,FALSE)] # 
      data_string <- unlist(str_split(eex_str, ","))[c(FALSE,TRUE)] # both length 6
      library(xts)
      suppressWarnings(recreated_xts <- xts(x = as.numeric(data_string[-1]), order.by = as.Date(index_string[-1] ))) # supress  NAs introduced by coercion
      colnames(recreated_xts) <- data_string[1]
      recreated_xts
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        • 2018-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多