[R] reason for error in small function?

Duncan Murdoch murdoch at stats.uwo.ca
Thu Oct 11 20:32:54 CEST 2007


On 10/11/2007 2:17 PM, Dale Steele wrote:
> Running the function below, tested using the cardiff dataset from
> splancs generates the following error.   What changes do I need to
> make to get the function to work?  Thanks.  --Dale
> 
>> gen.rpoints(events, poly, 99)
>> rpoints
> Error: object "rpoints" not found
> 
> # test spatial data
> library(splancs)
> data(cardiff)
> attach(cardiff)
> str(cardiff)
> events <- as.points(x,y)
> 
> ### non-working function ####
> 
> gen.rpoints <- function(events, poly, nsim){
> rpoints <- array(0, dim=c(nrow(events),2,nsim))
>   for (i in 1:nsim) {
>     rpoints[, ,i] <- csr(poly, nrow(events))
>   }
> }

You generate rpoints within the scope of the function, but you don't 
return it.  Change your function to

gen.rpoints <- function(events, poly, nsim){
   rpoints <- array(0, dim=c(nrow(events),2,nsim))
   for (i in 1:nsim) {
     rpoints[, ,i] <- csr(poly, nrow(events))
   }
   rpoints
}

and call it as

rpoints <- gen.rpoints(...)

(There are ways to create variables outside of the scope of the 
function, but you shouldn't use them.)

Duncan Murdoch



More information about the R-help mailing list