2017-09-03 29 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 = ','))