gpt4 book ai didi

r - 将 JSON 转换为数据框/CSV 时需要帮助导航列表

转载 作者:行者123 更新时间:2023-12-04 08:56:48 25 4
gpt4 key购买 nike

我正在尝试抓取一个 javascript 呈现的表,在尝试了 selenium 和 phantomJS 之后,我决定 JSON 将是最简单的方法。但是,我对 R 很陌生,并且不太擅长处理列表,因此我无法将数据转换为我想要的表格格式。我查看了许多解决方案,但由于某种原因,它们并不能真正适用于我拥有的 JSON。
JSON数据通过this URL呈现.和this是表所在的实际网站。
到目前为止,我所做的是尝试根据我从 stackoverflow 上的大多数答案中看到的内容,将 JSON 解析为 R 并将其强制转换为数据帧。

library(httr)
library(jsonlite)
rf <- GET(url) #the entire URL is very long so I'm not putting it here
rfc <- content(rf)
这样做会返回一个包含四个元素的大列表,即 rfc。然后我应用以下功能。
library(httr)
library(jsonlite)
json_file <- lapply(rfc, function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
})
这给我一个错误:
Error in x[sapply(x, is.null)] <- NA : invalid subscript type 'list'
鉴于我只需要列表的第二个元素,即信息所在的位置,我尝试对其进行子集化:
  json_file <- lapply(rfc[2], function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
})
这会返回一个大列表,大小为 12mb。当我尝试使用 as.data.frame 将其强制转换为数据帧时,R 返回我对 1 个变量的 506472 个观察值。不同的列都被压缩成一个,标题也不见了。
谁能告诉我应该怎么做?有一个免费的在线 JSON 转 CSV converter here这正是我需要的精美。这是它产生的:
enter image description here
不幸的是,这不是一个解决方案。因为我打算在 Shiny 中运行它,所以我想在 R 中做所有事情。感谢任何帮助,谢谢。

最佳答案

你需要带元素rfc$data$DailyProductionAndFlowList ,它本身实际上是一个单行数据帧的列表,并将它们绑定(bind)在一起。您需要覆盖 NULL值(value)观第一:

df <- do.call(rbind, lapply(rfc$data$DailyProductionAndFlowList, function(x) {
x[sapply(x, is.null)] <- "NULL"
as.data.frame(x, stringsAsFactors = FALSE)
}))
为了向您表明结果是合理的,我将其放入 tibble这里为了更好的打印:
as_tibble(df)
#> # A tibble: 3,997 x 11
#> GasDate FacilityId FacilityName LocationId LocationName Demand Supply
#> <chr> <int> <chr> <int> <chr> <dbl> <dbl>
#> 1 2020-0~ 520047 Eastern Gas~ 520008 Sydney 94.4 0
#> 2 2020-0~ 520047 Eastern Gas~ 520009 Canberra 16.5 0
#> 3 2020-0~ 520047 Eastern Gas~ 530015 Longford Hub 0 234.
#> 4 2020-0~ 520047 Eastern Gas~ 590011 Regional - ~ 22.4 0
#> 5 2020-0~ 520047 Eastern Gas~ 590012 Regional - ~ 2.68 19.4
#> 6 2020-0~ 520047 Eastern Gas~ 520008 Sydney 113. 0
#> 7 2020-0~ 520047 Eastern Gas~ 520009 Canberra 19.7 0
#> 8 2020-0~ 520047 Eastern Gas~ 530015 Longford Hub 0 225.
#> 9 2020-0~ 520047 Eastern Gas~ 590011 Regional - ~ 27.5 0
#> 10 2020-0~ 520047 Eastern Gas~ 590012 Regional - ~ 5.05 20.1
#> # ... with 3,987 more rows, and 4 more variables: TransferIn <dbl>,
#> # TransferOut <dbl>, HeldInStorage <chr>, LastUpdated <chr>

关于r - 将 JSON 转换为数据框/CSV 时需要帮助导航列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63776565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com