2

Suppose you inquire the following:

gtrends("google", geo="US")$interest_by_city

This returns how many searches for the term "google" occurred across cities in the US. However, it does not provide any information regarding which state each city belongs to.

I have tried merging this data set with several others including city and state names. Given that the same city name can be present in many states, it is unclear to me how to identify which city was the one Google Trends provided data for.

I provide below a more detailed MWE.

library(gtrendsR)
library(USAboundariesData) 

data1 <- gtrends("google", geo= "US")$interest_by_city
data1$city <- data1$location
data2 <- us_cities(map_date = NULL)
data3 <- merge(data1, data2, by="city")

And this yields the following problem:

    city        state 
  Alexandria   Louisiana      
  Alexandria   Indiana       
  Alexandria   Kentucky        
  Alexandria   Virginia       
  Alexandria   Minnesota      

making it difficult to know which "Alexandria" Google Trends provided the data for.

Any hints in how to identify the state of each city would be much appreciated.

Rebecca
  • 127
  • 1
  • 7
  • I don't know the ins & outs of `gtrendsr`, but I got curious. If you have an object `g` from `gtrends(...)`, `g$interest_by_dma` gives you metro areas with state names. You can also give a state in your `geo`, such as `geo = "US-CT"`; in that case, `g$interest_by_city` shows cities only in Connecticut. But if you want cities all over the US, that could get unwieldy. – camille Jun 06 '18 at 14:33
  • For anyone trying to run the code, according to the [github README](https://github.com/PMassicotte/gtrendsR), the CRAN version is no longer working, so the development version is recommended: `devtools::install_github("PMassicotte/gtrendsR)` – zack Jun 06 '18 at 15:01
  • @zack indeed, I should have mentioned that. – Rebecca Jun 06 '18 at 15:18
  • @camille I know I can do that by state which would solve the problem, but I need to do this all over US rather than just in one state (also inquiring within each state and then adding them together would not work because of the way the index is constructed). – Rebecca Jun 06 '18 at 15:18

1 Answers1

1

One way around this is to collect the cities per state and then just rbind the respective data frames. You could first make a vector of state codes like so

states <- paste0("US-",state.abb)

I then just used purrr for its map and reduce functionality to create a single frame

    data <- purrr::reduce(purrr::map(states, function(x){
      cities = gtrends("google", geo = x)$interest_by_city
    }),
    rbind)
gymbrane
  • 167
  • 9