Herman Toothrot
Herman Toothrot

Reputation: 1533

how to combine raster layers from a stack into a data frame R

I have a stack made of rasters

s<-stack(list of ASCI files)

I am trying to perform this operation

df<-as.data.frame(c(s[[1]],s[[2]],s[[2]],s[["bathymetry"]]))

but I get this error

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
cannot coerce class "structure("RasterLayer", package = "raster")" to a data.frame

When I perform this operation on a single raster such as

df<-as.data.frame(s[[1]])

everything works fine. But I have to extract many rasters and combined them in one dataframe. The only solution I see now is to extract them individually and then combined them, is there a better solution? I am working with hundreds of raster at a time.

EDIT: I should also add that this function goes inside a loop and I am only extracting a subset of the raster on each loop.

Upvotes: 2

Views: 6930

Answers (2)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

Or use...

data.frame( rasterToPoints( s ) )

Drop the columns you don't want afterwards.

Upvotes: 5

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

To apply a function to each element of a list, the apply family commands are helpful:

lapply( s, as.data.frame ) 

That returns a list of data.frames.

To restrict it to only the elements that you want, just subset to a smaller list beforehand.

s_small <- s[c(1,2,3,5)]
lapply( s_small, as.data.frame ) 

Upvotes: 1

Related Questions