Saving your API keys in some files outside your project enables you to share your codes without necessarily exposing your keys to others. There are several ways to achieve this, and here is one reference blog suggested by Prof. Suess.

After comparing the pros and cons, option 4 in the above blog is adopted. The idea is that you can create an environmental variable in .Renviron file, and call it by sys.getenv() when needed.

Step 0:

Install the R package usethis which has a function edit_r_environ() that we will use.

Step 1:

Open your home/global .Renvrion file

usethis::edit_r_environ()
## ● Edit /home/esuess/.Renviron
## ● Restart R for changes to take effect

this will open your .Renviron file, in which you can set a global envrionmental variable that contains your API key. In this case, I set GOOGLE_API = < my_google_API_key >

after saving your API key in the .Renvrion file, sometimes you need to restart R session for it to work.

Step 2:

Call your envrionmental variable when you need the API key

library(ggmap)
register_google(Sys.getenv("GOOGLE_API"))

geocode("golden gate bridge")
## Warning: geocode failed with status OVER_QUERY_LIMIT, location = "golden
## gate bridge"