将字符纬度/经度值转换为数字

时间:2018-06-27 20:49:03

标签: r leaflet

我有一个数据框df,其纬度和纵向字符值分别为东,西,北和南。通过将dfdf2列转换为数字并设置任何South和West值,将Latitude转换为所需输出Longitude的一种优雅方法否定的?

#MRE
library(tibble)

#input data set
df <- tribble(
  ~Country, ~Capital, ~Latitude, ~Longitude,
  "Afghanistan", "Kabul", "34.28N", "69.11E",
  "Albania", "Tirane", "41.18N", "19.49E",
  "Algeria", "Algiers", "36.42N", "03.08E",
  "American Samoa", "Pago Pago", "14.16S", "170.43W",
  "Andorra", "Andorra la Vella", "42.31N", "01.32E",
  "Angola", "Luanda", "08.50S", "13.15E" 
  )

# desired output

df2 <- tribble(
  ~Country, ~Capital, ~Latitude, ~Longitude,
  "Afghanistan", "Kabul", 34.28, 69.11,
  "Albania", "Tirane", 41.18, 19.49,
  "Algeria", "Algiers", 36.42, 03.08,
  "American Samoa", "Pago Pago", -14.16, -170.43,
  "Andorra", "Andorra la Vella", 42.31, 01.32,
  "Angola", "Luanda", -08.50, -13.15 
  )

预先感谢您的建议

2 个答案:

答案 0 :(得分:4)

http://<IP_ADDRESS>:3000

答案 1 :(得分:3)

使用tidyverse的解决方案。我们可以将LongitudeLongitude列分隔为数字和字母,然后如果是“ S”或“ W”,则添加减号。

library(tidyverse)

df2 <- df %>%
  separate(Latitude, into = c("Latitude", "Lat_Direction"), 
           sep = "(?=[A-Za-z])", convert = TRUE) %>%
  separate(Longitude, into = c("Longitude", "Long_Direction"), 
           sep = "(?=[A-Za-z])", convert = TRUE) %>%
  mutate(Latitude = ifelse(Lat_Direction %in% "S", -Latitude, Latitude),
         Longitude = ifelse(Long_Direction %in% "W", -Longitude,  Longitude)) %>%
  select(-ends_with("_Direction"))
df2
# # A tibble: 6 x 4
#   Country        Capital          Latitude Longitude
#   <chr>          <chr>               <dbl>     <dbl>
# 1 Afghanistan    Kabul                34.3     69.1 
# 2 Albania        Tirane               41.2     19.5 
# 3 Algeria        Algiers              36.4      3.08
# 4 American Samoa Pago Pago           -14.2   -170.  
# 5 Andorra        Andorra la Vella     42.3      1.32
# 6 Angola         Luanda               -8.5     13.2