4

I have a ESRI shapefile with which I do further work in R. It contains polygons of administrative units and their keys. Key value of one unit is incorrect and I need to rewrite it to be able to join my data later on (it is not practical to change the key value in my data).

Changing the key value in the sp object directly gives me an error:

srcShape[srcShape$KOD_ORP == "1000", ]$KOD_ORP <- "3018"

Error in as.vector(data) : 
  no method for coercing this S4 class to a vector

I am able to sidestep the error by first taking the entire data slot out of the sp object, changing it as data frame, and pasting it back in.

asdf <- srcShape@data
asdf[asdf$KOD_ORP == "1000", ]$KOD_ORP <- "3018"
srcShape@data <- asdf

I am however not comfortable rewriting the data slot in such a blunt way; it contains hundreds of polygons and I am afraid of messing up the polygon / key relationship.

Is there a safer solution for this? And is the behavior I see a bug, or a feature of Spatial DataFrame objects and exists there for a reason?

1
  • try srcShape$KOD_ORP[srcShape$KOD_ORP == "1000"] <- "3018" - no good reason, it's just that SpatialDataFrame is not actually a data.frame and not all the methods were implemented
    – mdsumner
    Nov 6, 2017 at 18:12

2 Answers 2

6

Work directly on slot data

srcShape@data[srcShape@data$KOD_ORP == "1000", "KOD_ORP"] <- "3018"
2
  • Please answer in more detail
    – BBG_GIS
    Nov 6, 2017 at 18:43
  • I have no idea how this works, but I am glad it does. Thanks! Nov 10, 2017 at 19:21
3

Your error:

srcShape[srcShape$KOD_ORP == "1000", ]$KOD_ORP <- "3018"
## Error in match(value, lx) : 'match' requires vector arguments
## In addition: Warning message:
## In checkNames(value) :
##   attempt to set invalid names: this may lead to problems later on. See ?make.names

If you don't have 3018 factor level in KOD_ORP field:

srcShape[srcShape$KOD_ORP == "1000", 'KOD_ORP'] <- "3018"
## Warning message:
## In `[<-.factor`(`*tmp*`, iseq, value = "3018") :
##   invalid factor level, NA generated

Workaround to solve your issue:

srcShape$KOD_ORP <- as.character(srcShape$KOD_ORP)

srcShape[srcShape$KOD_ORP == "1000", 'KOD_ORP'] <- "3018" # works

Best practice in my opinion:

srcShape@data$KOD_ORP <- as.character(srcShape@data$KOD_ORP)

field <- 'KOD_ORP'

srcShape@data[srcShape@data[,field] == "1000", field] <- "3018" #works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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