[R-sig-Geo] spsample random sampling a subset of polygons based on a variable from a different dataframe

kalee kathryn.lee1 at students.mq.edu.au
Mon Feb 25 03:38:03 CET 2013


Hi all,

Data background: I have a dataframe of fish telemetry locations where we
have to estimate the X and Y co-ordinates based on the depth at which the
fish is detected and the receiver number (combined into one attribute named
'RecDepth' within the dataframe; 20 fish each with 1,000-10,000 locations) .
I have a shapefile of the study area with the depth contours overlaided with
the detection range of each receiver. The depth contours have an accuracy of
+/-2m so I have buffered each of these polylines to give me the possible
area into which fish detection could be (polygons: with a attribute of
RecDepth that corresponds the the reciever number and depth of the contour).
The idea is to randomly select a point in each polygon corresponding to each
fish detection and then pass the results to calculate the home-range and run
1000 iterations to see how much the home-range estimates differ. 

Method and problem encountered: I now want to use spsample to randomly
select a point within each polygons for each fish detection. I've tried to
write a function to iterate through all the fish locations for each fish.
However, I'm having trouble with the function and I'm unsure why. I tried to
use the method suggested at
http://casoilresource.lawr.ucdavis.edu/drupal/node/644 but I can't figure
out how to select the correct polygons according the RecDepth in the
dataframe. 

Any help could be greatly appreciated. 
Thanks
Kate



My code is as follows:

library(sp)
data1 <- read.csv("Blues_COA_breed.csv", header= TRUE)
 
 str(data1)
##'data.frame':   102656 obs. of  9 variables:
## $ Date.Time: Factor w/ 56064 levels "1/08/2009 0:00",..: 40063 40064
40089 40100 40114 40119 40129 ##40134 40160 40166 ...
 ##$ ID       : int  1 1 1 1 1 1 1 1 1 1 ...
## $ sex      : Factor w/ 3 levels "female","male",..: 3 3 3 3 3 3 3 3 3 3
...
## $ sex_1    : int  3 3 3 3 3 3 3 3 3 3 ...
## $ RecDepth : int  608 608 608 608 508 608 608 608 606 606 ...
## $ Y        : num  -33.9 -33.9 -33.9 -33.9 -33.9 ...
## $ X        : num  151 151 151 151 151 ...
## $ Z        : int  8 8 8 8 8 8 8 8 6 6 ...
## $ Breeding : int  1 1 1 1 1 1 1 1 1 1 ...


#### Projection of shapefile is Australia Albers as follows:
 PROJECTION <- CRS("+proj=aea +lat_1=-18 +lat_2=-36 +lat_0=0 +lon_0=134
+x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs") 
 
 
 
 BCARshp <-
readShapeSpatial("Reef_depth_detectionrange_Buffer4m_ALbers.shp",
proj4string = PROJECTION)
 

str(BCARshp)
##Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
##  ..@ data       :'data.frame': 150 obs. of  6 variables:
##  .. ..$ COMMENT   : Factor w/ 1 level "Coogee Area": 1 1 1 1 1 1 1 1 1 1
...
##  .. ..$ depth_islw: int [1:150] 2 2 2 2 2 2 2 8 8 16 ...
##  .. ..$ Station   : num [1:150] 2 3 5 6 7 8 9 4 5 8 ...
##  .. ..$ Y         : num [1:150] -3834217 -3834550 -3834729 -3834818
-3834753 ...
##  .. ..$ X         : num [1:150] 1765872 1765908 1765672 1765450 1765176
...
##  .. ..$ RecDepth  : num [1:150] 202 302 502 602 702 802 902 408 508 816
...
##  .. ..- attr(*, "data_types")= chr [1:6] "C" "N" "N" "N" ...
##  ..@ polygons   :List of 150
##  .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
##  .. .. .. ..@ Polygons :List of 1
##  .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
##  .. .. .. .. .. .. ..@ labpt  : num [1:2] 1765872 -3834217
##  .. .. .. .. .. .. ..@ area   : num 1200
##  .. .. .. .. .. .. ..@ hole   : logi FALSE
##  .. .. .. .. .. .. ..@ ringDir: int 1
##  .. .. .. .. .. .. ..@ coords : num [1:164, 1:2] 1765898 1765898 1765897
1765897 1765897 ...
##  .. .. .. ..@ plotOrder: int 1
##  .. .. .. ..@ labpt    : num [1:2] 1765872 -3834217
##  .. .. .. ..@ ID       : chr "0"
##  .. .. .. ..@ area     : num 1200
##  .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
 ## .. .. .. ..@ Polygons :List of 1
 ## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
##  .. .. .. .. .. .. ..@ labpt  : num [1:2] 1765908 -3834550
##  .. .. .. .. .. .. ..@ area   : num 1572
##  .. .. .. .. .. .. ..@ hole   : logi FALSE
##  .. .. .. .. .. .. ..@ ringDir: int 1
##  .. .. .. .. .. .. ..@ coords : num [1:221, 1:2] 1765883 1765882 1765882
1765882 1765882 ...
##  .. .. .. ..@ plotOrder: int 1
##  .. .. .. ..@ labpt    : num [1:2] 1765908 -3834550
##  .. .. .. ..@ ID       : chr "1"
##  .. .. .. ..@ area     : num 1572
##  .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
##  .. .. .. ..@ Polygons :List of 1
##  .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
##  .. .. .. .. .. .. ..@ labpt  : num [1:2] 1765672 -3834729
##  .. .. .. .. .. .. ..@ area   : num 3334
##  .. .. .. .. .. .. ..@ hole   : logi FALSE
##  .. .. .. .. .. .. ..@ ringDir: int 1
 ## .. .. .. .. .. .. ..@ coords : num [1:494, 1:2] 1765498 1765498 1765498
1765498 1765498 ...
##  .. .. .. ..@ plotOrder: int 1
##  .. .. .. ..@ labpt    : num [1:2] 1765672 -3834729
##  .. .. .. ..@ ID       : chr "2"
##  .. .. .. ..@ area     : num 3334
## .. .. [list output truncated]
##  ..@ plotOrder  : int [1:150] 78 55 62 48 69 5 56 3 67 44 ...
##  ..@ bbox       : num [1:2, 1:2] 1764709 -3835506 1766254 -3833973
##  .. ..- attr(*, "dimnames")=List of 2
##  .. .. ..$ : chr [1:2] "x" "y"
##  .. .. ..$ : chr [1:2] "min" "max"
##  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots
##  .. .. ..@ projargs: chr "+proj=aea +lat_1=-18 +lat_2=-36 +lat_0=0
+lon_0=134 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m
+no_defs" 


 
 class(BCARshp)
##[1] "SpatialPolygonsDataFrame"
##attr(,"package")
##[1] "sp"

## starting with just fish ID 1

fish1 <- data1[data1$ID == 1, 5]

str(fish1)
## int [1:8185] 608 608 608 608 508 608 608 608 606 606 ...


d <- as.data.frame(fish1)

myfun <- function(d, k) {

BCARfish <- BCARshp[BCARshp$RecDepth == d[k,],] 

fish <- spsample(BCARfish, n = 1, type = "random", proj4string = PROJECTION,
iter= 10)

 xco <- fish at coords[[1]]
 yco<- fish at coords[[2]]

xy <- cbind(xco, yco)

return(xy)
}

fishdet <- rep(0, nrow(d))

for (j in 1:length(fishdet)) fishdet[j] <- myfun(d, j)

## ERROR I'M RECEIVING

Error in if (is.numeric(i) && i < 0) { : 
  missing value where TRUE/FALSE needed
In addition: There were 27 warnings (use warnings() to see them)


z <- as.matrix(d)
  
m <- dimnames(z)
  
l <-list(m[[1]], xy)

write.csv(l, file = paste("fish1_randpoint_test.csv"), row.names = F)

traceback()
12: stop("arguments imply differing number of rows: ", paste(unique(nrows), 
        collapse = ", "))
11: data.frame(NULL, c(1765491.27849468, -3834819.10145441), check.names =
FALSE, 
        stringsAsFactors = TRUE)
10: eval(expr, envir, enclos)
9: eval(as.call(c(expression(data.frame), x, check.names = !optional, 
       stringsAsFactors = stringsAsFactors)))
8: as.data.frame.list(x[[i]], optional = TRUE, stringsAsFactors =
stringsAsFactors)
7: as.data.frame(x[[i]], optional = TRUE, stringsAsFactors =
stringsAsFactors)
6: data.frame(x)
5: write.table(l, file = paste("fish1_randpoint_test.csv"), row.names = F, 
       col.names = TRUE, sep = ",", dec = ".", qmethod = "double")
4: eval(expr, envir, enclos)
3: eval(expr, p)
2: eval.parent(Call)
1: write.csv(l, file = paste("fish1_randpoint_test.csv"), row.names = F)




#### When I ran the following as a tester it worked ok


 BCARfish608 <- BCARshp[BCARshp$RecDepth == 608,]
 fish608 <- spsample(BCARfish608, n = 10, type = "stratified", proj4string =
PROJECTION)
 x_3 <- fish608 at coords[[1]]
 y_3 <- fish608 at coords[[2]]
 xy3 <- cbind(x_3, y_3)

 BCARfish426 <- BCARshp[BCARshp$RecDepth == 426,]
fish426 <- spsample(BCARfish426, n = 10, type = "stratified", proj4string =
PROJECTION)
 x_4 <- fish426 at coords[[1]]
y_4 <- fish426 at coords[[2]]
 xy4 <- cbind(x_4, y_4)

 BCARfish408 <- BCARshp[BCARshp$RecDepth == 408,]
 fish408 <- spsample(BCARfish408, n = 10, type = "stratified", proj4string =
PROJECTION)
 x_5 <- fish408 at coords[[1]]
 y_5 <- fish408 at coords[[2]]
 xy5 <- cbind(x_5, y_5)

fish <- rbind(xy1, xy2, xy3, xy4, xy5)


### the code for my home-range analysis would then be (this normally works
fine)

H.s <- Hpi(xy, binned = TRUE)
    
KDE <- kde(xy, H=H.s, binned = TRUE)
     
cont <- contourSizes(KDE, cont = c(95), approx = TRUE)
    
return(cont)
  

## plot of shapefile is attached
plot(BCARshp)

<http://r-sig-geo.2731867.n2.nabble.com/file/n7582766/BCARshp_plot.png> 

 
  




--
View this message in context: http://r-sig-geo.2731867.n2.nabble.com/spsample-random-sampling-a-subset-of-polygons-based-on-a-variable-from-a-different-dataframe-tp7582766.html
Sent from the R-sig-geo mailing list archive at Nabble.com.



More information about the R-sig-Geo mailing list