
Add a granularity_geo column to a data set
Source:R/add_variable_to_data_set.R
add_granularity_geo_to_data_set.RdDerives the geographic granularity label from the location_code column.
Adds the label as a new granularity_geo column, and changes x in place.
When location_reference is NULL, the granularity comes from the location
code prefix. When you supply a reference table, the granularity comes from
that table.
Arguments
- x
A data.table with a column named
location_code. Only a data.table method exists, so any other class raises "no applicable method".- location_reference
A data.table with columns
location_codeandgranularity_geoto use for lookup. WhenNULL(default), granularity comes from the location code prefix (e.g."county_nor03"->"county"). Itslocation_codevalues SHOULD be unique. A code that appears twice in the reference produces more labels thanxhas rows. The assignment then fails with "Supplied N items to be assigned to M items of column 'granularity_geo'".nor_locations_names()holds one such code today,"lab_nor084467", which two laboratories share.
See also
vignette("csdata", package = "csdata"), which calls this
function on a worked example. location_code_to_granularity_geo()
returns the same labels as a vector instead of writing them onto x.
Other data set column adders:
add_iso3_to_data_set()
Examples
library(data.table)
#>
#> Attaching package: ‘data.table’
#> The following object is masked from ‘package:base’:
#>
#> %notin%
data <- data.table(location_code = c("nation_nor", "county_nor03", "blah"))
csdata::add_granularity_geo_to_data_set(data)
print(data)
#> location_code granularity_geo
#> <char> <char>
#> 1: nation_nor nation
#> 2: county_nor03 county
#> 3: blah blah
library(data.table)
data <- data.table(location_code = c("nation_nor", "county_nor03", "blah"))
csdata::add_granularity_geo_to_data_set(data, location_reference = csdata::nor_locations_names())
print(data)
#> location_code granularity_geo
#> <char> <char>
#> 1: nation_nor nation
#> 2: county_nor03 county
#> 3: blah <NA>