Search code examples
rspatstat

Cannot modify subset of psp object


All,

I am trying to modify a subset of a psp object in the R package spatstat. Here is the code that is giving me an issue:

   set.seed(10)
   mat <- matrix(runif(40), ncol=4)
   mx <- data.frame(v1=sample(1:4,10,TRUE),
                    v2=factor(sample(letters[1:4],10,TRUE),levels=letters[1:4]))
   a <- as.psp(mat, window=owin(),marks=mx)
   #subset to marking v1 = 2, modify one of its endpoints
   a[a$marks$v1==2]$ends$x0<-rep(5,4)

this throws a warning at me:

Warning message: In a[a$marks$v1 == 2]$ends$x0 <- rep(5, 4) : number of items to replace is not a multiple of replacement length

What is the right way to modify some elements of a psp object? I commonly use this operation with dataframes and don't have an issue. My sense is that the subset operator ([) isn't set up for this operation with the psp class.

Thank you for reading; appreciate any help you may have.


Solution

  • The problem here is that you are trying to write to a subset of the psp object. Although the [ operator is defined for this class so you can extract a subset from it, the [<- operator is not defined, so you can't overwrite a subset.

    However, the member that you are trying to overwrite is a data frame, which of course does have a [<- operator defined. So all you need to do is write to that without subsetting the actual psp object.

    Here's a full reprex:

    library(spatstat)
    
    set.seed(10)
    mat <- matrix(runif(40), ncol = 4)
    mx  <- data.frame(v1 = sample(1:4, 10, TRUE),
                      v2 = factor(sample(letters[1:4], 10, TRUE),
                                  levels = letters[1:4]))
    a <- as.psp(mat, window = owin(), marks = mx)
    
    #subset to marking v1 = 2, modify one of its endpoints
    a$ends$x0[a$marks$v1 == 2] <- rep(5, 4)
    
    a
    #> marked planar line segment pattern: 10 line segments
    #> Mark variables:  v1, v2
    #> window: rectangle = [0, 1] x [0, 1] units
    

    Created on 2020-08-18 by the reprex package (v0.3.0)