2017-09-03 30 views
1

我试图将图书存储库中的数据转换成数字数据,以便我可以绘制图表。如何将Web抓取的数据转换为数字?

我的代码目前是:

selector <- ".rrp" 
library(rvest) 
url <- "https://www.bookdepository.com/bestsellers" 
doc <- read_html(url) 
prices <- html_nodes(doc, selector) 
html_text(prices) 
library(readr) 
Spiral <- read_csv("C:/Users/Ellis/Desktop/INFO204/Spiral.csv") 
View(Spiral) 

我试图清理数据:

text <- gsub('[$NZ]', '', Spiral) # removes NZ$ from data 

但现在的数据是这样的:

[1] "c(\"16.53\", \"55.15\", \"36.39\", \"10.80\", \"27.57\", \"34.94\", 
\"27.57\", \"22.06\", \"22.00\", \"16.20\", \"22.06\", \"22.06\", 
\"19.84\", \"19.81\", \"27.63\", \"22.06\", \"10.80\", \"27.57\", 
\"22.06\", \"22.94\", \"16.53\", \"25.36\", \"27.57\", \"11.01\", 
\"14.40\", \"15.39\")" 

,当我尝试运行:

as.numeric(text) 

我得到:

Warning message: 
NAs introduced by coercion 

如何清理以这样的方式NZ$从房价中剔除,我能够绘制的数据了“清理数据”

+0

也许您的数据为因子格式,而不是字符格式。在这种情况下请参阅:[*如何将因子转换为整数\数字而不会丢失信息?](https://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-一个整数数字 - 无需-A-失信息) – Jaap

回答

1

您有一个包含代码的字符串,而不是数字。您需要先评估代码。

as.numeric(eval(parse(text=text))) 
[1] 16.53 55.15 36.39 10.80 27.57 34.94 27.57 22.06 22.00 16.20 22.06 22.06 19.84 
[14] 19.81 27.63 22.06 10.80 27.57 22.06 22.94 16.53 25.36 27.57 11.01 14.40 15.39 
1

几个选项来获得期望的结果:

# option 1 
as.numeric(gsub('(\\d+.\\d+).*', '\\1', html_text(prices))) 
# option 2 
as.numeric(gsub('\\s.*$', '', html_text(prices))) 
# option 3 
library(readr) 
parse_number(html_text(prices)) 

所有结果:

[1] 21.00 9.99 31.49 19.49 6.49 13.50 22.49 11.99 11.49 7.99 10.99 7.99 10.99 9.99 7.99 9.99 11.49 8.49 11.99 9.99 14.95 8.99 20.13 13.50 8.49 6.49 

注:

  • 结果是欧元价格的向量。由于本地化价格可能会有所不同,当你从另一个县刮。
  • 当小数点位置符是html_text(prices)中的逗号(,)时,前两个选项可以更改为as.numeric(gsub('(\\d+),(\\d+).*', '\\1.\\2', html_text(prices)))以获得正确的结果。在这种情况下,第三个选项应更改为:parse_number(html_text(prices), locale = locale(decimal_mark = ','))