I'm developing a package that primarily consists of spatial data files for various geographies in New York City (boroughs, community districts, census tracts, etc.) as well as some helper functions to retrieve and filter these objects. I have each of the geographies saved as .rda files in the /data folder of the package so I can use the objects by referring to their name, like tracts_sf.
The main function in the package lets a user specify a geography (like borough, cd, tract) and returns an sf object with those boundaries. For example nyc_boundaries(geography = "borough") will return an sf object of the borough boundaries.
I'm wondering the best way to reference the appropriate data file to return (in this case boros_sf) in my function. Currently, I'm creating strings of the data files based on the input argument and then using get() to return the correct file, but this doesn't feel like the best way to do things. Here is a simplified version of my function:
Then the body of the main function can be adjusted. In this case, the nyc_boundaries function no longer has to worry about resolution by instead passing the value along to the helper functions.
if (geography == "borough") {
get_boros(resolution)
} else if (geography == "cd") {
get_cds(resolution)
} else {
get_tracts(resolution)
}
I hope this helps and best of luck with the package.
Thanks @nteetor! Your first suggestion is actually how I initially had it coded, but my real function can return more than just boroughs, cds, and tracts and it felt like there might be a better way that specifying each combination of geography and resolution. But get() feels somewhat brittle, so I might just go back to the other way.
I like to replace simple if-else chains with switch expressions. I've also come to appreciate "flat" code. It's easy to read and not much harder to write with a decent text editor (and R Studio is more than decent). More often, I'll use logic and string composition to write flat code, which I then copy into the R file.
Oh nice, I like both of these options. I didn't know about getExportedValue(), and that is pretty much what I was looking for in my original question. For now, I've decided to refactor the code a bit using more if/else statements because in my actual function, I need to assign additional variables and objects depending on the geography selection, so that seems to work better for me than switch() as @nweth suggested.