Last active
August 3, 2020 02:33
-
-
Save denironyx/9fa87a93c10ffa92608362ae770bd7bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## specify the require packages | |
packages = c( | |
"dplyr", | |
"sf", | |
"ghql", | |
"jsonlite" | |
) | |
## Now load or install & load all | |
package.check <- lapply( | |
packages, | |
FUN = function(x){ | |
if(!require(x, character.only = TRUE)){ | |
install.packages(x, dependencies = TRUE) | |
library(x, character.only = TRUE) | |
} | |
} | |
) | |
# EXTRACT DATA VIA GRAPHQL ==== | |
# create a link | |
` | |
x = 'https://census-api.frith.dev/graphql' | |
con = ghql::GraphqlClient$new(url = x) | |
# Loading the census api data schema into the R graphql client | |
query = 'query($type: String!){ | |
subplacebyName: places(type: $type){ | |
code | |
name | |
type {name descrip } | |
province { code name } | |
population | |
area | |
geom | |
} | |
}' | |
# Making a request and parsing in the query (schema) | |
qry <- ghql::Query$new() | |
qry$query('x', query) | |
qry$queries$x | |
# query the variable pine from the request sent. | |
variables <- list( | |
type = 'subplace' | |
) | |
# execute the query and variables %>% convert from json | |
result <- con$exec(qry$queries$x, variables = variables) %>% | |
jsonlite::fromJSON(flatten = T) | |
# WRANGLE DATA ==== | |
sub_place <- result$data$subplacebyName %>% | |
# convert coordinates to a list of points | |
mutate(geom.coordinates = lapply(geom.coordinates, function(x) list(list(matrix(x,ncol=2,byrow=FALSE))))) %>% | |
mutate(geometry = mapply( | |
function(type, points) { | |
# don't know if this is a valid assumption | |
# but get st_* function based on type column | |
get(paste0("st_",tolower(type)))(points) | |
}, | |
geom.type, | |
geom.coordinates, | |
SIMPLIFY = FALSE | |
)) %>% | |
mutate(geometry = geometry) %>% | |
st_sf(crs = "WGS84") %>% | |
select(-geom.coordinates) |
timelyportfolio
commented
Aug 3, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment