I have a marked spatial point pattern loaded in R (from Shapefile). This dataset has 4 different "classes" of marks: class A, class B, class C and class D. Each class of marks is categorical. One can imagine it as an attribute table, where each class of marks is a new categorical attribute (or column).

Now I need to work with the dataset using only class of marks A. Saying in other words, I need to reduce my dataset to have only one attribute, not 4 as before. Using split() does not work for my case.

What is the command for doing that in R?

2 Answers 2


You have to treat the @data slot (the data frame) a bit differently to reduce the number of attributes / columns:

Set the working directory and load the right library


Make a fake SPDF to work with, as OP describes

pts <- data.frame(x=1:5, y=1:5, A = 1:5, B = 1, C = 2, D = 3)
coordinates(pts) <- ~x+y
writeOGR(pts, dsn = ".", layer = "testPts", driver = "ESRI Shapefile")

Read the SPDF as a shapefile

pts <- readOGR(dsn = ".", layer = "testPts")

The data frame is in the @data slot:

# 'data.frame': 5 obs. of  4 variables:
# $ A: int  1 2 3 4 5
# $ B: num  1 1 1 1 1
# $ C: num  2 2 2 2 2
# $ D: num  3 3 3 3 3

What if we try to treat it like a normal data frame?

pts@data <- pts@data[, "val2"]
# Error in (function (cl, name, valueClass)  : 
# assignment of an object of class “factor” is not valid for @‘data’
# in an object of class “SpatialPointsDataFrame”; 
# is(value, "data.frame") is not TRUE

You can subset the slot by just indexing as if it were a vector

pts@data <- pts@data[2]
# 'data.frame': 5 obs. of  1 variable:
# $ B: num  1 1 1 1 1
  • @michalb, does this work in your case?
    – Simbamangu
    Jun 4, 2016 at 6:46

I think you need to subset your dataset using bracket notation. As an example:

point_pattern <- point_pattern[point_pattern$A == 1,]

  • 2
    This will not work as expected on a spatstat ppp object. Please try to provide specifics in your answer rather than being overly abbreviated. In this case you would specify that before coercion to a ppp object you could subset the the sp object using bracket notation. Please also note that it looks like the op has a character column, that is likely being coerced into a factor, and that after subseting the column will need to be refactorized to drop the missing levels. This can be done using "factor" however, "as.factor" would not drop the missing levels. May 20, 2016 at 14:20

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.