Skip to content
Prev 5029 / 29559 Next

Generating Random Transects of Same Length

As an spatstat aficionado, I would use the following code:

Enjoy!

Marcelino


library(spatstat)

# Define polygon, length of transect and number of (points)transects
data(letterR)
mywindow <- letterR
ltransect <- 0.3
npoints <- 100
s<- 1:npoints

# Generate random origin points
cosa <- runifpoint(npoints, w=mywindow)
plot(cosa)


cosaxy <- data.frame(cosa$x,cosa$y)

#compute a circle around each point
cosadisc<- apply(cosaxy,1, function(x) disc(r=ltransect, x))

# Test if every circle point is inside polygonal boundary
cosadisc.df <- lapply(cosadisc, function(W){
                          inside.owin(W$bdry[[1]]$x,W$bdry[[1]]$y 
,w=mywindow)})

#function to sample circle points within the window
samplea2 <- function(cosaxy, l1=cosadisc, l2=cosadisc.df){
result<-c(0,0)
for (i in 1:length(l1)){
                  truinside<-sum(l2[[i]])
                  inside 
<-cbind(l1[[i]]$bdry[[1]]$x,l1[[i]]$bdry[[1]]$y)[l2[[i]],]
                  result<-rbind(result,  inside[sample(1:truinside, size=1),])
}
result<-result[-1,]
result<-cbind(cosaxy,result)
return(result)
}

#the result is a matrix with x0,y0, x1, y1 for each transect
#Plot the random transects:

segmentos<-samplea2(cosaxy)
segments(segmentos[,1][s], segmentos[,2][s],segmentos[,3][s], segmentos[,4][s])
At 19:33 12/02/2009, Barry Rowlingson wrote:
________________________________

Marcelino de la Cruz Rot

Departamento de  Biolog?a Vegetal
E.U.T.I. Agr?cola
Universidad Polit?cnica de Madrid
28040-Madrid
Tel.: 91 336 54 35
Fax: 91 336 56 56
marcelino.delacruz at upm.es