我在将数据帧内的经/纬度数据从DMS(度分秒)转换为DD(十进制度数)时遇到很大麻烦。特别是当有NA条目时。我会喜欢类似于as.character()等的函数,但是显然不存在。 因此,我尝试使用as.numeric(char2dms())
这是我的数据示例:
library(dplyr)
library(tidyr)
library(sp)
df <- data.frame(field = paste("F", 1:10),
lat = c("52°48'48.8\"N","52°48'48.8\"N","52°48'59.27\"N","52°48'59.27\"N","52°48'26.57\"N","52°47'21.29\"N","52°37'21.30\"N",NA,NA,"52°2'54.53\"N"),
lon = c("9°13'56.0\"E","9°13'56.0\"E","9°14'5.98\"E","9°14'5.98\"E","9°13'56.43\"E","9°12'35.70\"E","9°6'4.23\"E",NA,NA,"10°45'47.62\"E"))
在R脚本专家中行之有效的方法:
df <- df%>%
mutate(lat= as.character(lat),
lon= as.character(lon))
df2<- df[!is.na(df$lat),] %>% # it is very important to get rid of NAs, because char2dms() is unfortunatel not able to simply ignore NA.
mutate(latDD = as.numeric(char2dms(lat, chd = "°", chm = "'", chs = "\"")),
lonDD = as.numeric(char2dms(lon, chd = "°", chm = "'", chs = "\"")))%>%
right_join(., df)
但是,当我保存脚本并通过source()从另一个脚本调用它时,它不再起作用。不幸的是,此示例也与我的实际情况有所不同,在该情况下,我从.txt文件加载数据。在此示例中,当我通过source()调用脚本时,奇怪的Â粘贴在°之前。
在实际情况下,错误消息是:
Error in mutate_impl(.data, dots) :
Evaluation error: missing value where TRUE/FALSE needed.
这很有可能来自char2dms()。
有人对此差异有解释吗?或替代source()?