Reputation: 439
I am trying to subset a 'SpatialPolygonsDataFrame' in R, but the methods proposed in other threads seem not to work. I am using R version 3.3.2 and I am accessing it through R studio on a mac.
Unfortunately, I cannot provide my dataset, (because I cannot subset my data).
This,
sp2 <- sp1[sp1@data$compound_found == 1, ]
produced the following error:
Error in sp1[sp1@data$compound_found == 1, ] : cannot get a slot ("Polygons") from an object of type "NULL"
despite
sp1@data$compound_found == 1
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE
[14] FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE
FALSE FALSE TRUE TRUE
[27] TRUE TRUE FALSE TRUE TRUE FALSE TRUE
TRUE FALSE FALSE FALSE TRUE
sp2 <- sp1["compound_found" == 1, ]
does not create an error, but creates an empty object
nrow(sp2@data) # returns 0
Any explanation why I cannot subset the way I was trying? How could I do it instead?
EDIT:
class(sp1)
returns
[1] "SpatialPolygonsDataFrame" attr(,"package") [1] "sp"
Upvotes: 0
Views: 2600
Reputation: 3369
Edited to describe troubleshooting that arrived at solution with help from OP.
A SpatialPolygonsDataFrame
usually can be subsetted as the OP has done above in the original question:
sp1[sp1@data$compound_found == 1, ]
Not sure where the error comes from without seeing the data. To troubleshoot, you can examine the structure of SpatialPolygonsDataFrame
to see where the error might be coming from.
str(sp1)
You can also separately subset @data
and @polygons
to check if it's pulling the right elements.
If you want to subset sp1@data
you can use:
sp1@data[1:ncol(sp1@data)][sp1@data$compound_found == 1,]
To get sp1@polygons
:
sp1@polygons[sp1@data$compound_found == 1]
Note that @data
and @polygons
should be the same length. See http://www.dpi.inpe.br/gilberto/tutorials/software/R-contrib/sp/html/SpatialPolygons.html
"data: the number of rows in data should equal the number of Polygons-class objects in Sr"
Check that nrow(sp1@data)
and length(sp1@polygons)
are the same.
Upvotes: 1