首页 > 解决方案 > 使用 rvest 在 R 中获取坐标的编码问题?

问题描述

我正在尝试从维基百科的表格中获取十进制坐标。下面的代码让我一直拥有一列纬度和一列经度,但我在将longitude列从字符转换为数字的最后一步失败了。相反,该latitude列转换得很好。

问题似乎是列中每个字符串末尾的“隐藏”字符longitudestr_length“计数”一个额外的字符而不是列值中可见的字符)。

这是编码问题吗?如何将longitude列转换为数字?

这段代码似乎让我最了解:

# load packages
library(xml2)
library(rvest)
library(dplyr)
library(stringr)
library(tidyr)
library(readr)

# get coordinates data
webpage_url <- "https://en.wikipedia.org/wiki/List_of_Premier_League_stadiums"
webpage <- xml2::read_html(webpage_url)

# put web data into dataframe
df1 <- rvest::html_table(webpage, fill = TRUE)[[1]] 

df2 <- df1 %>% 
  # split different coordinate formats
  mutate(temp_Coordinates = str_split(string = Coordinates, pattern = " / ")) %>% 
  # one coordinate format per row
  unnest(cols = temp_Coordinates) %>% 
  group_by(Stadium) %>% 
  # keep only 3rd row per stadium, i.e. decimal format of coordinates
  filter(row_number() == 3) %>% 
  ungroup() %>%
  # seperate coordinate pairs into individual columns for latitude and longitude
  separate(temp_Coordinates, c("latitude","longitude"), sep = " ") %>% 
  # remove semi-colon from end of latitude string
  mutate(latitude = str_replace(latitude, ";", ""))

问题似乎出在最后一步,longitude从字符转换为数字(导致一列 NA):

df3 <- df2 %>% 
  # convert latitude from character to numeric 
  mutate(latitude = as.numeric(latitude)) %>% 
  # convert longitude from character to numeric
  mutate(longitude = as.numeric(longitude))

手动分配一个复制粘贴的值 fromlongitude会返回此错误(注意在将字符串粘贴到控制台时出现奇怪的问号字符);

x <- "-2.96083�" 错误:在第 2 行读取 MBCS 字符时出现 EOF

有人知道如何更改格式以便我可以转换为数字吗?

谢谢!

标签: rencodingcharacter-encodingtidyverservest

解决方案


您可以从一组不同的节点中提取值并分配给数据框

library(rvest)
library(magrittr)

webpage_url <- "https://en.wikipedia.org/wiki/List_of_Premier_League_stadiums"
webpage <- read_html(webpage_url) 
df1 <- webpage %>% html_node('table') %>% html_table(fill = T)
geos <- webpage %>% html_nodes('.geo') %>% html_text() %>% str_split_fixed(., ';',2)
df1$latitude <- geos[, 1] %>% as.double()
df1$longitude <- geos[, 2] %>% as.double()

print(head(df1,1))

推荐阅读