0

I have a SpatialPolygonsDataFrame with 14 different polygons. Each polygon currently has an attribute column "id", which is a single string that identifies the original colony, year, and season the polygon represents (e.g. "COL1_2010_Winter").

I want to now add 3 more attribute columns to my spdf object, "colony", "year, and "season", and populate each row with the info taken from "id". Is this possible?

The ultimate goal is to plot the polygons by year and colony, with different colors for winter and summer.

4
  • Yes, you can split the data. I recommend you to use sf instead of sp (unless there is a specific reason for using sp). With sf, you can easily use dplyr verbs for that task. Upload reproducible data for post this as an answer
    – aldo_tapia
    Commented Jun 17, 2022 at 17:29
  • Thanks - I need to find out how to produce a reproducible example of a SPDF... bear with me
    – user303287
    Commented Jun 17, 2022 at 17:39
  • You can use dput(spdf_object)
    – aldo_tapia
    Commented Jun 17, 2022 at 17:45
  • I understand that reproducible example can in some cases be helpful. In this case, it may not be needed for an answer. See my answer, received from a colleague.
    – user303287
    Commented Jun 17, 2022 at 18:32

1 Answer 1

1

The answer to my question is that i can actually treat it like a normal dataframe. The following works:

let my SpatialPolygonsDataFrame be "spdf_object", with attribute "id", where all my 14 id's are in the following format "COL1_2019_Winter"; "COL1_2020_Winter"; "COL1_2020_Summer","COL2_2019_Winter", etc.

I can use the following to add the columns "colony", "year", and "season", using info from column "id".

spdf_object$colony <- substr(spdf_object$id, 0, 3) 
spdf_object$year <- substr(spdf_object$id, 5, 8) 
spdf_object$season<- substr(spdf_object$id, 10, 15)
3
  • 1
    For sp class objects, with assignment, it is safer to invoke the data slot using eg., x@data$colony <- substr(x$id, 0, 3). However, I would recommend using sf class objects as sp is being retired. The workflow would be the same, sans the data slot, and just like interacting with a data.frame. You can use st_read to import your data or x <- as(x, "sf") to coerce and sp to sf object. Commented Jun 17, 2022 at 19:15
  • You mean "normal data frame", not "normal shapefile".
    – Spacedman
    Commented Jun 18, 2022 at 13:49
  • @Spacedman - yes! thanks you, have amended my answer.
    – user303287
    Commented Jun 18, 2022 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.