J.Babt
J.Babt

Reputation: 1

R raster::extract fails to create data.frame

I’m looking to extract values from a raster using raster::extract and an sf object. However I’m having some difficulties. I wish to create a data frame which contains the cellnumbers (to derive XY values), the extracted cell value and an ID field (for if I extract from multiple lines). I do that with the following:

  dtm_values <- raster::extract(raster, transect_sf, cellnumbers = TRUE, df = TRUE)

However I cannot extract to a data frame as I get the following error:

Error in do.call(rbind, sapply(1:length(res), function(x) if (!is.null(res[[x]])) cbind(x,  : 
  second argument must be a list

As a workaround I am extracting as a list (i.e. df = FALSE) and converting this to a dataframe with as.data.frame(), which is working fine but inefficient. Having looked around the internet I have found one other reference to this issue which is a bug report from 2018: https://r-forge.r-project.org/tracker/index.php?func=detail&aid=6570&group_id=294&atid=1189

This appears to be the issue that I am facing. This link also includes the following reproducible example, which I can replicate:

r = raster(nrow=45, ncol=90) 
r[] = 1:ncell(r) 

transect_sf = st_sfc(st_linestring(rbind(c(-175, -85), c(175, 85)))) %>%
    st_sf() 
raster::extract(r, transect_sf, along = TRUE, df = TRUE) 
 #> Error in do.call(rbind, sapply(1:length(res), function(x) if (!is.null(res[[x]])) cbind(x, : second argument must be a list

Am I making a mistake here or is this a bug with the raster package?

Thanks for your help in advance.

I'm using: R - 3.6.1 on Windows 7, raster 3.0-7 , sf 0.9-0.

Upvotes: 0

Views: 354

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

This is a bug. It has now been fixed in the development version of raster (version 3.1-2)

Upvotes: 1

Related Questions