Learn R Programming

tmaptools (version 2.0)

append_data: Append data to a shape object

Description

Data, in the format of a data.frame, is appended to a shape object. This is either done by a left join where keys are specified for both shape and data, or by fixed order. Under coverage (shape items that do not correspond to data records), over coverage (data records that do not correspond to shape items respectively) as well as the existence of duplicated key values are automatically checked and reported via console messages. With under_coverage and over_coverage the under and over coverage key values from the last append_data call can be retrieved. Tip: run append_data without assigning the result to check the coverage. Note that this function supports sf objects, but still uses sp-based methods (see details).

Usage

append_data(shp, data, key.shp = NULL, key.data = NULL,
  ignore.duplicates = FALSE, ignore.na = FALSE,
  fixed.order = is.null(key.data) && is.null(key.shp))

under_coverage()

over_coverage()

Arguments

data

data.frame

key.shp

variable name of shp map data to be matched with key.data. If not specified, and fixed.order is FALSE, the ID's of the polygons/lines/points are taken.

key.data

variable name of data to be matched with key.shp. If not specified, and fixed.order is FALSE, the row names of data are taken.

ignore.duplicates

should duplicated keys in data be ignored? (FALSE by default)

ignore.na

should NA values in key.data and key.shp be ignored? (FALSE by default)

fixed.order

should the data be append in the same order as the shapes in shp?

Value

Shape object with appended data. Tip: run append_data without assigning the result to check the coverage.

Details

This function supports sf objects, but still uses sp-based methods, from the packages sp, rgeos, and/or rgdal. Alternatively, the tidyverse method left_join can be used.

Examples

Run this code
# NOT RUN {
if (require(tmap)) {
    data(World)

    f <- tempfile()
    download.file("http://kejser.org/wp-content/uploads/2014/06/Country.csv", destfile = f)
    domain_codes <- read.table(f, header=TRUE, sep="|")
    unlink(f)

    domain_codes <- subset(domain_codes, select = c("Alpha3Code", "TopLevelDomain"))
    domain_codes$Alpha3Code <- toupper(domain_codes$Alpha3Code)

    World <- append_data(World, domain_codes, key.shp = "iso_a3", key.data = "Alpha3Code",
    					 ignore.na = TRUE)

    # codes in the data, but not in Europe:
    oc <- over_coverage()
    oc$value

    # Countries without appended data:
    uc <- under_coverage()

    current_mode <- tmap_mode("view")
    qtm(World[uc$id,], text="name")

    # plot the result
    qtm(World, text="TopLevelDomain")
    tmap_mode(current_mode)
}
# }

Run the code above in your browser using DataLab