Home > other >  Extract the Correct Column from the Result of lapply in R
Extract the Correct Column from the Result of lapply in R

Time:01-23

I have a bathymetry raster and a bounding gridded shapefile.

I cannot isolate the 'values' column of the list that lapply produces.

The intention is to use the raster mean values column as a new column in the shapefile

library("sf")
library("raster")

download.file("https://transfer.sh/T8BJjo/Raster.tif", destfile = "Raster.tif", method = "curl")

Raster_Data <- raster("Raster.tif")

download.file("https://transfer.sh/FgqHhS/HexGridShapefile.gpkg", destfile = "HexGridShapfile.tif", method = "curl")

GridShapefile <- st_read("HexGridShapfile.tif")

Raster_Values <- extract(Raster_Data, GridShapefile)

Mean_Raster_Values <- lapply(Raster_Values, FUN=mean)

#Extract Mean Values and set them to Column of Shapefile
GridShapefile$Raster_Values <- Mean_Raster_Values[[3]]  # INCORRECT IMPLEMENTATION

The last line should be assigning entire third column from Mean_Raster_Values list object but [[3]] only provides the third row

How to access the third column from Mean_Raster_Values ?

CodePudding user response:

We may need to unlist the list to a vector as each list element is numeric and is a single value (mean returns a single numeric output)

GridShapefile$Raster_Values <- unlist(Mean_Raster_Values)

-output

> head(GridShapefile)
Simple feature collection with 6 features and 1 field
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: 1.276447 ymin: 39.20347 xmax: 1.351447 ymax: 39.47771
Geodetic CRS:  WGS 84
                            geom Raster_Values
1 POLYGON ((1.301447 39.24677...     -691.8400
2 POLYGON ((1.301447 39.33337...     -967.5200
3 POLYGON ((1.301447 39.41997...    -1357.5200
4 POLYGON ((1.326447 39.20347...     -588.7440
5 POLYGON ((1.326447 39.29007...     -811.5081
6 POLYGON ((1.326447 39.37667...    -1156.5040

If we have use sapply instead of lapply, it would have returned a vector as by default simplify = TRUE in sapply and thus we could have directly created the column

GridShapefile$Raster_Values <- sapply(Raster_Values, FUN=mean)
  • Related