【问题标题】:How to convert web scraped data into numeric?如何将网络抓取的数据转换为数字?
【发布时间】:2017-09-03 10:49:01
【问题描述】:

我正在尝试将从图书存放处抓取的数据转换为数字数据,以便我可以绘制它。

我目前的代码是:

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$ 从价格中删除并且我能够绘制“清理后的数据”

【问题讨论】:

标签: r type-conversion rvest


【解决方案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

【讨论】:

    【解决方案2】:

    获得理想结果的几种选择:

    # 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 = ','))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多