[英]How can I convert Degree minute sec to Decimal in R?
I have this dataframe: 我有这个数据框:
Lat Long
59 44 50 151 45 11
59 49 28 154 52 56
59 46 42 150 45 15
How can I convert this into decimal columns? 如何将其转换为十进制列?
lat is in dd mm ss and long is in ddd mm ss lat以dd mm ss为单位,long以ddd mm ss为单位
I found a similar solution here, but couldn't adapt the regex for my case. 我在这里找到了类似的解决方案,但是无法适应我的情况下的正则表达式。
Converting geo coordinates from degree to decimal 将地理坐标从度转换为小数
Try this function: 试试这个功能:
angle2dec <- function(angle) {
angle <- as.character(angle)
x <- do.call(rbind, strsplit(angle, split=' '))
x <- apply(x, 1L, function(y) {
y <- as.numeric(y)
y[1] + y[2]/60 + y[3]/3600
})
return(x)
}
Then you can apply it to each column in your data frame: 然后,您可以将其应用于数据框中的每一列:
new_df <- apply(df, 2L, angle2dec)
new_df
Lat Long
[1,] 59.74722 151.7531
[2,] 59.82444 154.8822
[3,] 59.77833 150.7542
or just 要不就
df$Lat <- angle2dec(df$Lat)
df$Long <- angle2dec(df$Long)
May I suggest the tidyr
approach: 我可以建议
tidyr
方法:
df <- data.frame( Lat=c("59 44 50","59 49 28","59 46 42"),
Long=c("151 45 11","154 52 56","150 45 15"))
library(tidyr); library(dplyr)
df %>%
separate(Lat, paste("lat",c("d","m","s"), sep="_") ) %>%
separate(Long, paste("long",c("d","m","s"), sep="_" ) ) %>%
mutate_each(funs(as.numeric)) %>%
transmute(lat_dec=lat_d + lat_m/60 + lat_s/60^2,
long_dec=long_d + long_m/60 + long_s/60^2)
# lat_dec long_dec
# 1 59.74722 151.7531
# 2 59.82444 154.8822
# 3 59.77833 150.7542
Here's an idea using splitstackshape
: 这是一个使用
splitstackshape
的想法:
library(dplyr)
library(splitstackshape)
df %>%
cSplit(c("Lat", "Long"), sep = " ") %>%
transmute(Lat = Lat_1 + Lat_2 / 60 + Lat_3 / 60^2,
Long = Long_1 + Long_2 / 60 + Long_3 / 60^2)
Which gives: 这使:
# Lat Long
#1: 59.74722 151.7531
#2: 59.82444 154.8822
#3: 59.77833 150.7542
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.