Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected behavior in as.contour #966

Closed
jmsigner opened this issue Jan 5, 2023 · 1 comment
Closed

Unexpected behavior in as.contour #966

jmsigner opened this issue Jan 5, 2023 · 1 comment

Comments

@jmsigner
Copy link

jmsigner commented Jan 5, 2023

Background

While migrating from raster to terra I found an unexpected behavior in the function as.contour() if the resulting SpatVect was only one single feature. Changing sapply() to lapply() on line 103 solved it:

terra/R/plot.R

Line 103 in c133566

y <- sapply(1:length(z), function(i) cbind(z[[i]]$level, i, z[[i]]$x, z[[i]]$y))

Example

as.contour_asis <- function(x, maxcells=100000, ...) {
            x <- spatSample(x[[1]], size=maxcells, method="regular", as.raster=TRUE)
            z <- grDevices::contourLines(x=xFromCol(x,1:ncol(x)), y=yFromRow(x, nrow(x):1), z=t(as.matrix(x, wide=TRUE)[nrow(x):1,]), ...)
            y <- sapply(1:length(z), function(i) cbind(z[[i]]$level, i, z[[i]]$x, z[[i]]$y))
            y <- do.call(rbind, y)
            y[] <- as.numeric(y)
            u <- unique(y[,1])
            y[,1] <- match(y[,1], u)
            colnames(y)[3:4] <- c("x", "y")
            vect(y, "lines", atts=data.frame(level=u), crs=crs(x))
}

as.contour_fixed <- function(x, maxcells=100000, ...) {
            x <- spatSample(x[[1]], size=maxcells, method="regular", as.raster=TRUE)
            z <- grDevices::contourLines(x=xFromCol(x,1:ncol(x)), y=yFromRow(x, nrow(x):1), z=t(as.matrix(x, wide=TRUE)[nrow(x):1,]), ...)
            y <- lapply(1:length(z), function(i) cbind(z[[i]]$level, i, z[[i]]$x, z[[i]]$y)) # changed to lapply here
            y <- do.call(rbind, y)
            y[] <- as.numeric(y)
            u <- unique(y[,1])
            y[,1] <- match(y[,1], u)
            colnames(y)[3:4] <- c("x", "y")
            vect(y, "lines", atts=data.frame(level=u), crs=crs(x))
}


# Creating a dummy data set
xy <- expand.grid(x = seq(-10, 10, 0.1), 
                  y = seq(-10, 10, 0.1))
xy$z <- pexp(0.75, sqrt(xy$x^2 + xy$y^2))
r <- rast(xy)

as.contour_asis(r, levels = c(0.4, 0.5))  # works as expected
as.contour_asis(r, levels = c(0.4))  # error

as.contour_fixed(r, levels = c(0.4, 0.5)) # works as expected
as.contour_fixed(r, levels = c(0.4)) # works as expected
@rhijmans
Copy link
Member

rhijmans commented Jan 5, 2023

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants