-
Notifications
You must be signed in to change notification settings - Fork 0
/
Week7.rmd
74 lines (65 loc) · 2.06 KB
/
Week7.rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
---
title: "Week7"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Assignment – Working with XML and JSON in R
*Pick three of your favorite books on one of your favorite subjects. At least one of the books should have more
than one author. For each book, include the title, authors, and two or three other attributes that you find
interesting.
Take the information that you’ve selected about these three books, and separately create three files which
store the book’s information in HTML (using an html table), XML, and JSON formats (e.g. “books.html”,
“books.xml”, and “books.json”)...
Write R code, using your packages of choice, to load the information from each of the three sources into
separate R data frames. Are the three data frames identical?*
## Load libraries
```{r}
library(RCurl)
library(xml2)
library(XML)
library(htmltab)
library(jsonlite)
library(tibble)
library(tidyverse)
```
## Define connections
```{r}
htmlFile = "https://raw.githubusercontent.com/dburtsev/CUNYR/master/books.html"
jsonFile = "https://raw.githubusercontent.com/dburtsev/CUNYR/master/books.json"
xmlFile = "https://raw.githubusercontent.com/dburtsev/CUNYR/master/books.xml"
```
## Load data into R
```{r}
var_html = htmltab(doc = htmlFile, which = 1)
var_json = jsonlite::fromJSON(jsonFile)
var_xml = read_xml(xmlFile)
```
## Display data from html
```{r}
class(var_html)
head(var_html)
```
## Display data from json
```{r}
class(var_json)
head(var_json)
```
## Display data from xml
```{r}
class(var_xml)
xml_name(var_xml)
xml_text(var_xml)
xml_structure(var_xml)
```
## Convert xml to data frame
```{r}
doc = xmlParse(var_xml)
df = xmlToDataFrame(getNodeSet(doc, "//books/book"))
class(df)
head(df)
```
## Conclusion
We can load data from HTML, JSON, and XML format into R data frame. Data frames are not the same, there is double-quote at the end of the title 'Data Science for Business' from XML and authors are processed differently.
The data needs to be clean up.