R,获取城市的经度/纬度数据,并将其添加到我的数据框 [英] R, get longitude/latitude data for cities and add it to my dataframe

查看:218
本文介绍了R,获取城市的经度/纬度数据,并将其添加到我的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to get longitude/latitude data for the cities in my dataframe and add as 2 columns in my frame. I'm new to R and I do not know how to do it. Could someone help me on this

我的框架:

> 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


推荐答案

参考您的原始问题 http://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)

这篇关于R,获取城市的经度/纬度数据,并将其添加到我的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆