gpt4 book ai didi

r - 将字符 lat/lng 值转换为数字

转载 作者:行者123 更新时间:2023-12-01 09:45:00 32 4
gpt4 key购买 nike

我有一个数据框 df,其中包含带有东、西、北和南指定的纬度和经度字符值。通过转换 LatitudeLongitudedf 转换为所需输出 df2 的优雅方法是什么?列作为数字并使任何 South 和 West 值为负?

#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
)

提前感谢您的友好建议

最佳答案

library(dplyr)
df %>%
mutate_at(vars(Latitude, Longitude),
funs(as.numeric(gsub("[NE]$", "", gsub("^(.*)[WS]$", "-\\1", .)))))
# # A tibble: 6 × 4
# Country Capital Latitude Longitude
# <chr> <chr> <dbl> <dbl>
# 1 Afghanistan Kabul 34.28 69.11
# 2 Albania Tirane 41.18 19.49
# 3 Algeria Algiers 36.42 3.08
# 4 American Samoa Pago Pago -14.16 -170.43
# 5 Andorra Andorra la Vella 42.31 1.32
# 6 Angola Luanda -8.50 13.15

关于r - 将字符 lat/lng 值转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071179/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com