【发布时间】:2020-06-19 17:13:34
【问题描述】:
我想从tomtom 网站提取som 城市交通数据。例如,我想从下面的网站下载“每小时拥堵水平”图表的数据。
https://www.tomtom.com/en_gb/traffic-index/wuhan-traffic/
是否可以使用 R 下载该数据?
如果有任何帮助,我将非常高兴。
【问题讨论】:
标签: r data-extraction
我想从tomtom 网站提取som 城市交通数据。例如,我想从下面的网站下载“每小时拥堵水平”图表的数据。
https://www.tomtom.com/en_gb/traffic-index/wuhan-traffic/
是否可以使用 R 下载该数据?
如果有任何帮助,我将非常高兴。
【问题讨论】:
标签: r data-extraction
这相对简单。图表中的数据来自从对 TomTom 的 API 的 GET 请求收到的 json 文件。以下是在tibble 中获取每小时数据的方法:
res <- httr::GET("https://api.midway.tomtom.com/ranking/liveHourly/CHN_wuhan")
tibble::as_tibble(apply(do.call(rbind, content(res, "parsed")$data), 2, unlist))
#> # A tibble: 168 x 7
#> JamsDelay TrafficIndexLive UpdateTime JamsLength JamsCount TrafficIndexWee~
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1.3 0 1.59e12 1.3 1 0
#> 2 3.6 0 1.59e12 1.3 3 0
#> 3 2.4 0 1.59e12 0.4 2 0
#> 4 1.2 0 1.59e12 2.5 2 0
#> 5 28 1 1.59e12 3.1 10 1
#> 6 47.2 7 1.59e12 11.3 21 7
#> 7 119. 10 1.59e12 19.5 40 12
#> 8 142. 15 1.59e12 34.2 58 14
#> 9 103. 14 1.59e12 23.9 40 14
#> 10 55.2 11 1.59e12 8.1 19 9
#> # ... with 158 more rows, and 1 more variable: UpdateTimeWeekAgo <dbl>
由reprex package (v0.3.0) 于 2020 年 6 月 19 日创建
【讨论】:
添加艾伦的好答案:
如果数据以 JSON 格式交付,您还可以使用 R 的 jsonlite 包:
library(jsonlite)
url_path <- "https://api.midway.tomtom.com/ranking/liveHourly/CHN_wuhan"
res <- jsonlite::fromJSON(url_path)
head(res$data)
JamsDelay TrafficIndexLive UpdateTime JamsLength JamsCount TrafficIndexWeekAgo UpdateTimeWeekAgo
1 1.3 0 1.591988e+12 1.3 1 0 1.591384e+12
2 3.6 0 1.591992e+12 1.3 3 0 1.591387e+12
3 2.4 0 1.591996e+12 0.4 2 0 1.591391e+12
4 1.2 0 1.591999e+12 2.5 2 0 1.591394e+12
5 28.0 1 1.592006e+12 3.1 10 1 1.591401e+12
6 47.2 7 1.592009e+12 11.3 21 7 1.591404e+12
【讨论】: