Search code examples
rspatialr-sf

Add column into sf() dataframe in r?


I have an sf object as obtained from here.

extraWD <- "."
if (!file.exists(file.path(extraWD, "departement.zip"))) {
  githubURL <- "https://github.com/statnmap/blog_tips/raw/master/2018-07-14-introduction-to-mapping-with-sf-and-co/data/departement.zip"
  download.file(githubURL, file.path(extraWD, "departement.zip"))
  unzip(file.path(extraWD, "departement.zip"), exdir = extraWD)
}

departements_L93 <- st_read(dsn = extraWD, 
                            layer = "DEPARTEMENT",
                            quiet = TRUE) %>% st_transform(2154)

I want to add another column with values to plot. How can I add this column while keeping the sf() structure so I can plot it? If this is not possible, how can I generate the sf() dataframe from scratch?


Solution

  • {sf} package objects are modified dataframes, so any technique you would use for adding a column to a regular dataframe should work.

    I recommend either one of the dplyr::*_join() family functions to add a column by key, or dplyr::mutate() to add a calculated column.

    But base R techniques, such as creating a column via the dollar notation, should work too...