3

Sorry if this is repetitive, but I've looked everywhere and can't seem to find anything that addresses my specific problem in R. I have a column with city names:

cities <-data.frame(c("Sydney", "Dusseldorf", "LidCombe", "Portland"))
colnames(cities)[1]<-"CityName"  

Ideally I'd like to attach a column with either the lat/long for each city or the time zone. I have tried using the "ggmap" package in R, but my request exceeds the maximum number of requests they allow per day. I found the "geonames" package that converts lat/long to timezones, so if I get the lat/long for the city I should be able to take it from there.

Edit to address potential duplicate question: I would like to do this without using the ggmap package, as I have too many rows and they have a maximum # of requests per day.

cheesetaco
  • 145
  • 1
  • 1
  • 8
  • Do you need a one to one ralationship? What about cities that cross time zones? – Jeffrey Sep 10 '17 at 00:25
  • @Jeffrey , one to one relationship would be ideal. I am assuming the likelihood of that happening in my data is low and if it does, its impact on the data negligible – cheesetaco Sep 10 '17 at 01:08

1 Answers1

5

You can get at least many major cities from the world.cities data in the maps package.

## Changing your data to a vector
cities <- c("Sydney", "Dusseldorf", "LidCombe", "Portland")

## Load up data
library(maps)
data(world.cities)

world.cities[match(cities, world.cities$name), ]
            name country.etc     pop    lat   long capital
36817     Sydney   Australia 4444513 -33.87 151.21       0
10026 Dusseldorf     Germany  573521  51.24   6.79       0
NA          <NA>        <NA>      NA     NA     NA      NA
29625   Portland   Australia    8757 -38.34 141.59       0

Note: LidCombe was not included.
Warning: For many names, there is more than one world city. For example,

world.cities[grep("Portland", world.cities$name), ]
          name country.etc    pop    lat    long capital
29625 Portland   Australia   8757 -38.34  141.59       0
29626 Portland         USA 542751  45.54 -122.66       0
29627 Portland         USA  62882  43.66  -70.28       0

Of course the two in the USA are Portland, Maine and Portland, Oregon. match is just giving the first one on the list. You may need to use more information than just the name to get a good result.

G5W
  • 36,531
  • 10
  • 47
  • 80
  • I avoided the double city issue by splitting it up by country. Obviously cities like "Portland" in the US will remain problematic, but it should be negligible. Thanks! – cheesetaco Sep 11 '17 at 17:57
  • I almost included that in the answer - guessing that you were interested in Australia. – G5W Sep 11 '17 at 17:58
  • I am, but am just going to have to write a script for both US and Aus. Dang Portland, Aus is causing such a headache. Your script still saved me though! – cheesetaco Sep 11 '17 at 18:07
  • This gets us from city name to lat / lon, but not from lat lon to time zone – stevec Sep 20 '20 at 16:02