【问题标题】:Web scraping and reshaping data网页抓取和重塑数据
【发布时间】:2021-03-12 06:32:36
【问题描述】:

我从网站抓取整理表格时遇到问题。 我想从下面的链接中获取表格(带有标题 V1 到 V5),但我未能在 R studio 中将其转换为相同的格式。

这就是我正在做的事情

url <- "https://www.r-bloggers.com/2018/08/using-control-charts-in-r/"
library(rvest)
library(tidyverse)
h <- read_html(url)
tab <- h %>% html_nodes("table") 
tab <- tab[[2]] %>% html_table()
 
tab <- separate_rows(tab, 1, sep = " ")
tab <- tab[8:132,]
tab <- as.data.frame(tab)
 
tab1 <- data.frame(c("V1", "V2", "V3", "V4", "V5"))
tab1 <- tab1 %>% setNames("Cat")
tab2 <- cbind(tab1,tab)
 
tab3 <- tab2 %>% spread(key = Cat, X1)

这是结果

Error: Each row of output must be identified by a unique combination of keys.
Keys are shared for 125 rows:
* 1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96, 101, 106, 111, 116, 121
* 2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97, 102, 107, 112, 117, 122
* 3, 8, 13, 18, 23, 28, 33, 38, 43, 48, 53, 58, 63, 68, 73, 78, 83, 88, 93, 98, 103, 108, 113, 118, 123
* 4, 9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64, 69, 74, 79, 84, 89, 94, 99, 104, 109, 114, 119, 124
* 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125

那么我应该怎么做才能获得与网站相同的表格?

如果你能想到从这个网站上获取表格的更好方法,请告诉我。

P/s:我正在自学R编程,请教我!

干杯。

【问题讨论】:

  • 仅供参考,“报废”的意思是扔掉 - 正确的术语是 scraping

标签: r web-scraping rvest


【解决方案1】:

这是一种方法:

library(rvest)

url <- "https://www.r-bloggers.com/2018/08/using-control-charts-in-r/"

url %>%
  read_html %>%
  html_nodes('table') %>%
  .[[2]] %>%
  html_table() %>%
  dplyr::pull(X1) %>%
  stringr::str_extract_all('\\d+\\.\\d+') %>%
  .[[1]] %>%
  matrix(ncol = 5, byrow = TRUE) %>%
  as.data.frame() %>% type.convert() -> tab

tab
#     V1   V2   V3   V4   V5
#1  1.45 1.56 1.40 1.45 1.33
#2  1.75 1.53 1.55 1.42 1.42
#3  1.60 1.41 1.35 1.52 1.36
#4  1.53 1.58 1.54 1.71 1.55
#5  1.48 1.34 1.64 1.59 1.46
#6  1.69 1.55 1.49 1.61 1.47
#...
#...

【讨论】:

  • 不错。 type.convert() 是否检查数据结构并确定最合适的数据类型,然后将其应用于所有值(保留为默认值时)?
  • 是的,没错。它分别处理每一列,并为该列应用最合适的数据类型。因此,当您在其中一列中有字符值时,这也将起作用。
  • 看起来 data.frame 也进行了隐式转换。
  • 看起来它已经将值转换为数字,但它们仍然是字符。你可以通过添加... data.frame %&gt;% str来检查。
  • 如果您的数据中没有标题as.data.frame 默认生成列名称为V1V2V3....如果您使用data.frame,它将生成@ 987654328@, X2, X3....
猜你喜欢
  • 1970-01-01
  • 2021-10-15
  • 2021-12-28
  • 1970-01-01
  • 2021-08-29
  • 2015-09-16
  • 2020-06-18
相关资源
最近更新 更多