r - 使用 rvest 在 R 中获取坐标的编码问题?
问题描述
我正在尝试从维基百科的表格中获取十进制坐标。下面的代码让我一直拥有一列纬度和一列经度,但我在将longitude
列从字符转换为数字的最后一步失败了。相反,该latitude
列转换得很好。
问题似乎是列中每个字符串末尾的“隐藏”字符longitude
(str_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
有人知道如何更改格式以便我可以转换为数字吗?
谢谢!
解决方案
您可以从一组不同的节点中提取值并分配给数据框
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))
推荐阅读
- flutter - 当索引值在可观察的列表上为真时,卡片颜色不会改变
- wcf - wcf Web 服务仅在 xamarin.forms 应用程序中使用时生成异步方法
- r - 在 R 中的简单线性回归中,我如何重新调整年龄以估计其每年/5 年/10 年的 beta 系数?
- html - 在引导程序上删除空格白色
- td-engine - TDengine数据库调试时如何记录sql命令?
- ios - SwiftUI 导航。推送后立即弹出视图。怎么修?
- elasticsearch - 没有写入时,为什么 Elasticsearch 每隔“n”秒执行一次索引?
- android - 前台服务中的静态变量
- node.js - mongo 对象 id 未在数组对象内部生成
- javascript - 无法通过 PUT 请求更新 mongodb 中的数据(Nodejs ExpressJS)