3

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?

1

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

require(rgdal)
setwd("~/workspace/TEMP/")

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:

str(pts@data)
# '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]
str(pts)
# 'data.frame': 5 obs. of  1 variable:
# $ B: num  1 1 1 1 1
  • @michalb, does this work in your case? – Simbamangu Jun 4 '16 at 6:46
0

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. – Jeffrey Evans May 20 '16 at 14:20

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.