我正在尝试将维基百科关于美国最高法院大法官的数据加载到 R 中:
library(rvest)
html = html("http://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States")
judges = html_table(html_nodes(html, "table")[[2]])
head(judges[,2])
[1] "Wilson, JamesJames Wilson" "Jay, JohnJohn Jay†"
[3] "Cushing, WilliamWilliam Cushing" "Blair, JohnJohn Blair, Jr."
[5] "Rutledge, JohnJohn Rutledge" "Iredell, JamesJames Iredell"
问题是数据格式不正确。而不是我在实际 HTML 表中看到的名称(“James Wilson”),它实际上出现了两次,一次是“Lastname, Firstname”,然后又是“Firstname Lastname”。
原因是每个实际上都包含一个不可见的:
<td style="text-align:left;" class="">
<span style="display:none" class="">Wilson, James</span>
<a href="/wiki/James_Wilson" title="James Wilson">James Wilson</a>
</td>
具有数值数据的列也是如此。我猜这个额外的代码是对 HTML 表进行排序所必需的。但是,我不清楚在尝试从 R 中的表创建 data.frame 时如何删除这些跨度。