【问题标题】:How to modify R data frame so that coordinates are readable by ggplot如何修改 R 数据框以便 ggplot 可以读取坐标
【发布时间】:2020-07-06 09:34:04
【问题描述】:

我正在使用绘制犯罪地点地图的数据集。不幸的是,犯罪数据的位置以文本格式(x.xxxxxx, y.yyyyyyyy)存储在单个列中。小数位数因数据点而异。该数据集包含数百个数据点。如何修改此特定列,以便将 x 和 y 坐标分开并存储在数据框中的两个单独列中?

感谢您的帮助

【问题讨论】:

  • 一个小的reproducible example 会有很大帮助。您可能可以从数据中获得 5 到 8 个示例行,并确保包含您想要的输出。还包括您迄今为止尝试过的所有步骤。

标签: r dataframe ggplot2 mapping ggmap


【解决方案1】:

这是一个假数据的例子:

# Fake data
d = data.frame(x=c("(8.4344, 93.593)", "(6.44, 91.3)"), stringsAsFactors=FALSE)

library(tidyverse)

d %>% 
  # Remove parentheses
  mutate(x = gsub("\\(|\\)", "", x)) %>% 
  # Separate into two columns
  separate(x, into=c("lat","lon"), sep=", ") %>% 
  # Convert to numeric
  mutate(across(lat:lon, as.numeric))
     lat    lon
1 8.4344 93.593
2 6.4400 91.300

或者,使用正则表达式提取经纬度:

d %>% 
  mutate(lat = str_extract(x, "(?<=\\()[0-9-\\.]*"),
         lon = str_extract(x, "(?<=, )[0-9-\\.]*"),
         across(lat:lon, as.numeric))

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    相关资源
    最近更新 更多