- Hands-On Exploratory Data Analysis with R
- Radhika Datar Harish Garg
- 486字
- 2021-06-24 14:10:42
Getting data into R from web APIs using the httr R package
We need to implement the following steps to extract data using the httr package in R workspace:
First, we load the httr package:
library(httr)
We then call GET function and pass it as a URL:
r <- GET("http://httpbin.org/get")
This gives us a response object that can be processed further for data. To start with, we can print out the response object to get some information about the data:
>r
Response [http://httpbin.org/get]
Date: 2019-01-18 03:45
Status: 200
Content-Type: application/json
Size: 326 B
{
"args": {},
"headers": {
"Accept": "application/json, text/xml, application/xml, */*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "libcurl/7.58.0 r-curl/3.2 httr/1.3.1"
},
"origin": "106.200.254.84",
...
We can get to the data contained in the response using the content method. For example, to get the body of the request as a raw vector, the following command is executed:
> content(r, "raw")
[1] 7b 0a 20 20 22 61 72 67 73 22 3a 20 7b 7d 2c 20 0a 20 20 22 68 65 61 64 65 72 73 22 3a 20
[31] 7b 0a 20 20 20 20 22 41 63 63 65 70 74 22 3a 20 22 61 70 70 6c 69 63 61 74 69 6f 6e 2f 6a
[61] 73 6f 6e 2c 20 74 65 78 74 2f 78 6d 6c 2c 20 61 70 70 6c 69 63 61 74 69 6f 6e 2f 78 6d 6c
[91] 2c 20 2a 2f 2a 22 2c 20 0a 20 20 20 20 22 41 63 63 65 70 74 2d 45 6e 63 6f 64 69 6e 67 22
[121] 3a 20 22 67 7a 69 70 2c 20 64 65 66 6c 61 74 65 22 2c 20 0a 20 20 20 20 22 43 6f 6e 6e 65
[151] 63 74 69 6f 6e 22 3a 20 22 63 6c 6f 73 65 22 2c 20 0a 20 20 20 20 22 48 6f 73 74 22 3a 20
[181] 22 68 74 74 70 62 69 6e 2e 6f 72 67 22 2c 20 0a 20 20 20 20 22 55 73 65 72 2d 41 67 65 6e
[211] 74 22 3a 20 22 6c 69 62 63 75 72 6c 2f 37 2e 35 38 2e 30 20 72 2d 63 75 72 6c 2f 33 2e 32
[241] 20 68 74 74 72 2f 31 2e 33 2e 31 22 0a 20 20 7d 2c 20 0a 20 20 22 6f 72 69 67 69 6e 22 3a
[271] 20 22 31 30 36 2e 32 30 30 2e 32 35 34 2e 38 34 22 2c 20 0a 20 20 22 75 72 6c 22 3a 20 22
[301] 68 74 74 70 3a 2f 2f 68 74 74 70 62 69 6e 2e 6f 72 67 2f 67 65 74 22 0a 7d 0a
>
In the next section, we will learn to get data into R by scraping the web using the rvest package.
推薦閱讀
- Mastering Spark for Data Science
- 協(xié)作機(jī)器人技術(shù)及應(yīng)用
- 數(shù)據(jù)庫(kù)系統(tǒng)原理及應(yīng)用教程(第5版)
- TensorFlow Reinforcement Learning Quick Start Guide
- FPGA/CPLD應(yīng)用技術(shù)(Verilog語(yǔ)言版)
- 嵌入式操作系統(tǒng)原理及應(yīng)用
- Linux嵌入式系統(tǒng)開(kāi)發(fā)
- 人工智能技術(shù)入門(mén)
- 嵌入式Linux系統(tǒng)實(shí)用開(kāi)發(fā)
- 青少年VEX IQ機(jī)器人實(shí)訓(xùn)課程(初級(jí))
- 貫通Hibernate開(kāi)發(fā)
- 百度智能小程序:AI賦能新機(jī)遇
- Mastering Microsoft Dynamics 365 Customer Engagement
- 商務(wù)智能
- ORACLE數(shù)據(jù)庫(kù)技術(shù)實(shí)用詳解