【问题标题】:R, get longitude/latitude data for cities and add it to my dataframe [closed]R,获取城市的经度/纬度数据并将其添加到我的数据框[关闭]
【发布时间】:2016-03-14 22:34:20
【问题描述】:

我想在我的数据框中获取城市的经度/纬度数据,并在我的框架中添加为 2 列。我是 R 新手,我不知道该怎么做。 有人可以帮我解决这个问题

我的框架:

> data <- read.xlsx("example_city.xlsx", 1)
> data
        City Country
1  Stockholm  Sweden
2       Oslo  Norway
3       Rome   Italy
4       Rome   Italy
5  Stockholm  Sweden
6  Stockholm  Sweden
7      Paris  France
8      Paris  France
9    Hamburg Germany
10     Paris  France
11     Paris  France

【问题讨论】:

  • 我不会对您投反对票,但您确实需要先对此进行一些讨论,然后再在这里提问。向我们展示您的数据是一个好的开始。你具体尝试了什么?你搜索过这些吗?例如“R中的地理定位城市”.

标签: r dataframe latitude-longitude


【解决方案1】:

参考你原来的问题https://stackoverflow.com/questions/20936263/use-ggplot2-to-plot-cities-on-a-map

# data 
cities <- sort(c(rep('Stockholm', 3), 'Oslo', 'Rome', 'Rome', 'Paris', rep('Bonn',10), 'Paris', 'Paris', 'Stockholm'))

# get frequencies
freq <- as.data.frame(table(cities))
library(plotrix)
freq$Freq <- rescale(freq$Freq, c(1,10)) # c(scale_min, scale_max)

# get cities latitude/longitude - kindly provided by google:
library(ggmap)
lonlat <- geocode(unique(cities)) 
cities <- cbind(freq, lonlat)

# get matches between names {maps} names and EU country names
library(maps)
eu <- c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czech Republic", 
        "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", 
        "Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", 
        "Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", 
        "Slovenia", "Spain", "Sweden", "United Kingdom")
warning("No matches in database for ", paste(setdiff(eu, map_data('world')$region), collapse=", ")) 
europe <- map_data('world', region=eu)

# plot
library(ggplot2)
ggplot(europe, aes(x=long, y=lat, group=group)) +
  geom_polygon(fill="white", colour="black") +
  xlim(-20, 40) + ylim(25,75) +
  geom_point(data=cities, inherit.aes=F, aes(x=lon, y=lat, size=Freq), colour="red", alpha=.8) + 
  geom_text(data=cities, inherit.aes=F, aes(x=lon, y=lat, label=cities), vjust=1, colour="red", alpha=.5)

【讨论】:

  • 太好了,非常感谢...这对我的原始数据集真的很有帮助!!
  • 祝你好运,@jonas。除了繁琐的国名匹配之外,肯定会有更多的绊倒危险。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 2014-01-23
  • 2011-05-01
  • 2013-12-09
相关资源
最近更新 更多