我正在使用 R 編程語言。
我正在嘗試從維基百科中抓取第二張表。
下面,我概述了我在嘗試抓取此表時嘗試的兩種不同方法(方法 1、方法 2)中使用的策略:
# METHOD 1
library(rvest)
url <- "https://en.wikipedia.org/wiki/List_of_municipalities_in_Ontario"
html <- read_html(url)
final <- data.frame(html %>%
html_element("table.wikitable.sortable") %>%
html_table())
> dim(final)
[1] 33 7
在Method 1中,代碼似乎可以運行,但該表似乎比維基百科頁面上的實際表“小”得多(即行數更少)。
然后我嘗試了以下代碼:
# METHOD 2
library(httr)
library(XML)
r <- GET(url)
final <- readHTMLTable(
doc=content(r, "text"))
在Method 2中,該表似乎比以前的結果“大”得多(我仍然不確定是否包含了表的所有行):
111 9,545 9,631 -0.9% 555.96 17.2/km2
[ reached 'max' / getOption("max.print") -- omitted 307 rows ]
但是當我嘗試將方法 2的結果保存為資料框時,出現以下錯誤:
final = data.frame(final)
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, :
arguments imply differing number of rows: 34, 418, 14, 8, 4
有人可以告訴我我做錯了什么以及如何解決這個問題嗎?
謝謝!
參考:
- 在 R 中匯入維基百科表格
- 從 R 中的 Wikipedia 抓取表格
uj5u.com熱心網友回復:
這是一種方法。它將兩個表都提取到一個串列中,最后使用標準提取運算子[來獲取第二個表。這會提取一個子串列,以提取表本身使用[[.
suppressPackageStartupMessages({
library(rvest)
library(dplyr)
})
url <- "https://en.wikipedia.org/wiki/List_of_municipalities_in_Ontario"
html <- read_html(url)
html %>%
html_elements(".wikitable") %>%
html_table() -> wikitables
html %>%
html_elements(".wikitable") %>%
html_element("caption") %>%
html_text() %>%
sub("\\n$", "", .) -> wikitables_names
names(wikitables) <- wikitables_names
wikitables[2]
#> $`List of local municipalities in Ontario`
#> # A tibble: 417 × 9
#> `Name[12]` Statu…1 CSD t…2 Censu…3 2021 …? 2021 …? 2021 …? 2021 …? 2021 …?
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 Name[12] Status… CSD ty… Census… Popula… Popula… Change Land a… Popula…
#> 2 Addington Hi… Lower-… Townsh… Lennox… 2,534 2,318 9.3% 1,293.… 2.0/km2
#> 3 Adelaide Met… Lower-… Townsh… Middle… 3,011 2,990 0.7% 331.11 9.1/km2
#> 4 Adjala-Tosor… Lower-… Townsh… Simcoe 10,989 10,975 0.1% 371.53 29.6/k…
#> 5 Admaston/Bro… Lower-… Townsh… Renfrew 2,995 2,935 2.0% 519.59 5.8/km2
#> 6 Ajax Lower-… Town Durham 126,666 119,677 5.8% 66.64 1,900.…
#> 7 Alberton Single… Townsh… Rainy … 954 969 ?1.5% 116.60 8.2/km2
#> 8 Alfred and P… Lower-… Townsh… Presco… 9,949 9,680 2.8% 391.79 25.4/k…
#> 9 Algonquin Hi… Lower-… Townsh… Halibu… 2,588 2,351 10.1% 999.69 2.6/km2
#> 10 Alnwick/Hald… Lower-… Townsh… Northu… 7,473 6,869 8.8% 398.25 18.8/k…
#> # … with 407 more rows, and abbreviated variable names 1?`Status[12]`,
#> # 2?`CSD type[4]`, 3?`Census division[32][33][34]`,
#> # ??`2021 Census of Population[4]`, ??`2021 Census of Population[4]`,
#> # ??`2021 Census of Population[4]`, ??`2021 Census of Population[4]`,
#> # ??`2021 Census of Population[4]`
使用reprex v2.0.2創建于 2022-09-13
要強制表格上課"data.frame",請改用以下內容。
html %>%
html_elements(".wikitable") %>%
html_table() %>%
purrr::map(as.data.frame) -> wikitables
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506643.html
