I have a SpatialLinesDataFrame file named "Sldf" which lacks attributes for each line (see table of sample data below). I have a separate data.frame (from a .csv) named "fsub" with attributes that I would like to merge to the SpatialLinesDataFrame file.

The "DataID" column in the fsub data.frame and the Slot "Id" number in the SpatialLinesDataFrame link the two. See screenshot below for where the unique identifier appears in the SpatialLinesDataFrame file.

How would I complete this operation? I tried the basic merge function but I don't think that works with spatial files.

Sample data "fsub" data.frame    
DataID  source  target  value
    30  Dis1    France  5
    35  Dis1    USA     10
    52  Dis1    Albania 15
    80  Dis1    Austria 20
    121 Dis2    Mexico  506

enter image description here


It would be helpful if you posted your code. There is now a special merge function that is called for sp class objects that addresses the sorting issues with base merge breaking the slot relationships. You can bring up help for the sp version of merge using ?sp::merge.

The slot id should be the same as the rownames in the @data slot. As such, you can use merge with "row.names" as the argument for by.x

merge(Sldf, fsub, by.x = "row.names", by.y = "DataID")

If you receive an error, it could be due to rownames being a character vector (the have to be) and your "DataID" being numeric. You can fix this easily by adding a dummy ID feild that is created by coercing "DataID" to a character vector, ie., fsub$TmpID <- as.character(fsub$DataID) You would then use this in place of "DataID".

Your Answer

