Hi Ross,

Thank-you for your reply. I also contacted Mike Sumner and he had a look at
the data. The initial problem was there were some fish detections at
receiver depths that were outside the detection range area and therefore
there was no polygon within the shapefile to sample from. After looking
through the dataset and detection records a few of these detections were
likely 'false' detections and so I excluded them from the analysis.

In answer to your question: 'Why don't you simply specify n = number of
detections at that receiver as you did on the 'tester'?' There are 90
unique polygons which I need to sample between 1 and 10636 locations from
so I wanted to run it through a loop to avoid selecting the polygons
manually as in the tester.

However, I've now run into another problem. When I run the code I get the
warning "number of items to replace is not a multiple of replacement
length" even though when I test the two vector lengths they are the same
length. The data links and code is as follows:

*The data is available here*:

<a href="
http://www.filefactory.com/file/184orpn0ctbr/n/BCAR_allrec_depth_400mdetct_ALBERS_sbn
">BCAR_allrec_depth_400mdetct_ALBERS_sbn</a>

<a href="
http://www.filefactory.com/file/3cztp27ug0xt/n/BCAR_allrec_depth_400mdetct_ALBERS_dbf
">BCAR_allrec_depth_400mdetct_ALBERS_dbf</a>

<a href="
http://www.filefactory.com/file/3rhzeggmivfr/n/BCAR_allrec_depth_400mdetct_ALBERS_prj
">BCAR_allrec_depth_400mdetct_ALBERS_prj</a>

<a href="http://www.filefactory.com/file/4hfpotb0m06x/n/Blues_COA_breed_csv
">Blues_COA_breed_csv</a>

<a href="
http://www.filefactory.com/file/56njraetymfh/n/BCAR_allrec_depth_400mdetct_ALBERS_shp_xml
">BCAR_allrec_depth_400mdetct_ALBERS_shp_xml</a>

<a href="
http://www.filefactory.com/file/6kzvtw7vwm1z/n/BCAR_allrec_depth_400mdetct_ALBERS_shx
">BCAR_allrec_depth_400mdetct_ALBERS_shx</a>

<a href="
http://www.filefactory.com/file/7doddw120b73/n/BCAR_allrec_depth_400mdetct_ALBERS_sbx
">BCAR_allrec_depth_400mdetct_ALBERS_sbx</a>

<a href="
http://www.filefactory.com/file/8lg1j53c9mp/n/BCAR_allrec_depth_400mdetct_ALBERS_shp
">BCAR_allrec_depth_4

*My code is as follows:*

library(ks)
library(rgdal)
library(proj4)
library(maptools)
library(sp)
##library('taRifx.geo')


setwd("/Users/kalee/Documents/MQ/Blues/Blues_KDE2/Feb 2013/")
data1 <- read.csv("Blues_COA_breed.csv", header= TRUE)

 str(data1)
#$ 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("BCAR_allrec_depth_400mdetct_ALBERS.shp",
proj4string = PROJECTION)


class(BCARshp)
########################################################################################

## RANDOM POINT ALLOCATION

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

d <- as.data.frame(fish1)

sort(unique(d$fish1))
sort(unique(BCARshp$RecDepth))


d2 <- d[d$fish1 %in% c(BCARshp$RecDepth), ]

d3 <- as.numeric(d2)

sort(unique(d3))
sort(unique(BCARshp$RecDepth))


myfun <- function(d3, k) {

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

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

     xco <- fish@coords[,1]
     yco<- fish@coords[,2]
     xy <- cbind(xco, yco)
     return(xy)
  }

fishdet <- rep(0, length(d3))

for (i in 1:length(fishdet)) fishdet[i] <- myfun(d3, i)

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

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


I also tried:

d2 <- d[d$fish1 %in% c(BCARshp$RecDepth), ]
d3 <- as.data.frame(table(d2))

myfun <- function(d3, k) {

    x <- d3[k]
     BCARfish <- BCARshp[BCARshp$RecDepth == x, ]

     xx <- d3$Freq[k]

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

     xco <- fish@coords[,1]
     yco<- fish@coords[,2]
     xy <- cbind(xco, yco)
     return(xy)
  }



fishdet <- rep(0, length(d3))

for (i in 1:length(fishdet)) fishdet[i] <- myfun(d3[i])



Any insight you have as to what I'm doing wrong would be greatly
appreciated. I'm still not overly confident on writing my own functions (or
diagnosing problems within them).

Many thanks,
Kate


On 27 February 2013 15:45, Ross Dwyer <ross.dwyer@uq.edu.au> wrote:

> Hi Kate,
>
> It's always tough to decipher errors in code without the raw data to play
> around with. However I appreciate that the acoustic detection datasets can
> be huge (102656 in your case) and not easy to push around.
>
> From reading your code, I'm unsure why you need to run the for-loop on the
> 'myfun' function. Why don't you simply specify n = number of detections at
> that receiver as you did on the 'tester'? For-loops are computationally
> demanding and good to avoid when possible. This would would dramatically
> speed up the run-time and may fix your error.
>
> If this doesn't work, try posting your data on something like
> http://www.filefactory.com/. You may get more responses on your  query
> that way.
>
> Cheers, Ross
>
> Dr Ross Dwyer | University of Queensland | Email: ross.dwyer@uq.edu.au |
> http://www.uq.edu.au/eco-lab/ross-dwyer
>
>
>
>
> -----Original Message-----
> From: r-sig-geo-bounces@r-project.org [mailto:
> r-sig-geo-bounces@r-project.org] On Behalf Of kalee
> Sent: Monday, 25 February 2013 12:38 PM
> To: r-sig-geo@r-project.org
> Subject: [R-sig-Geo] spsample random sampling a subset of polygons based
> on a variable from a different dataframe
>
> 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@coords[[1]]
>  yco<- fish@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@coords[[1]]
>  y_3 <- fish608@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@coords[[1]]
> y_4 <- fish426@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@coords[[1]]
>  y_5 <- fish408@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.
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



-- 
Kate Lee
PhD candidate
Marine Mammal Research Group
Graduate School of Environment
MACQUARIE UNIVERSITY NSW 2109

Phone: +61 (0)2 9850 7980
www.mq.edu.au

CRICOS Provider No 00002J

This message is intended for the addressee named and may...{{dropped:9}}

