Klausos Klausos
Klausos Klausos

Reputation: 16050

How to simplify FOR loops in R?

for(i in 1:100)
{
  for(j in 1:100)
  {
       hdist <- rgeos::gDistance(xySpatialLines[[i]], xySpatialLines[[j]], byid=FALSE, hausdorff=TRUE)
       distances[i,j] <- dist 
  }
}

Is there any way to simplify j loop to get something like this:

for(i in 1:100)
{
  distances[i,j] <- lapply(???)  # or sapply?
}

UPDATE:

The data stored in xySpatialLines[[i]] - these are SpatialLines objects:

library(sp)
xySpatialLines <- vector(mode = "list", length = 2)
x1 <- c(1,4,5,3,2)
y1 <- c(2,5,3,6,7)
x2 <- c(4,4,6,3,2)
y2 <- c(8,5,2,6,1)
xy1 <- cbind(x1,y1)
xy2 <- cbind(x2,y2)
xy1.sp = sp::SpatialPoints(xy1)
xy2.sp = sp::SpatialPoints(xy2)
spl1 <- sp::SpatialLines(list(Lines(Line(xy1.sp), ID="a")))
spl2 <- sp::SpatialLines(list(Lines(Line(xy2.sp), ID="b")))
xySpatialLines[[1]] = spl1
xySpatialLines[[2]] = spl2

Upvotes: 1

Views: 190

Answers (1)

Se&#241;or O
Se&#241;or O

Reputation: 17412

You can use outer:

distances = outer(xySpatialLines, xySpatialLines, FUN = gDistance, byid=FALSE, hausdorff = TRUE)

Upvotes: 4

Related Questions