I don't have an asc file handy right now for a reproducible example. I want to be able to read an asc file into R and then convert it to raster using the sf package. How can I accomplish that in R?
dummy Example:
library(sf)
x = read.table("Myfile.asc")
xx <- st_as_sf(x) #convert to sf
#now save xx as sf spatial object
Use terra
package.
If you want to convert the raster to a sf
object, the way to do it is to convert first to polygons with terra
and then use st_as_sf
:
# Create an asc file for the example
library(terra)
#> terra 1.7.23
f <- system.file("ex/elev.tif", package = "terra")
r <- rast(f)
writeRaster(r, "Myfile.asc")
# Head
cat(readLines("Myfile.asc")[1:6], sep = "\n")
#> ncols 95
#> nrows 90
#> xllcorner 5.741666666667
#> yllcorner 49.441666666667
#> cellsize 0.008333333333
#> NODATA_value -32768
Now the code snippet:
library(terra)
# Read with terra as raster
xx <- rast("Myfile.asc")
xx
#> class : SpatRaster
#> dimensions : 90, 95, 1 (nrow, ncol, nlyr)
#> resolution : 0.008333333, 0.008333333 (x, y)
#> extent : 5.741667, 6.533333, 49.44167, 50.19167 (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84
#> source : Myfile.asc
#> name : elevation
#> min value : 141
#> max value : 547
plot(xx)
Basically you are done, but if you want to convert this to sf
(i.e. convert raster data to vector data) you can do:
# Convert to vector in sf
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
sfobj <- st_as_sf(as.polygons(xx, dissolve = FALSE))
sfobj
#> Simple feature collection with 4608 features and 1 field
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: 5.75 ymin: 49.45 xmax: 6.525 ymax: 50.18333
#> Geodetic CRS: WGS 84
#> First 10 features:
#> elevation geometry
#> 1 529 POLYGON ((6 50.175, 6 50.18...
#> 2 542 POLYGON ((6.008333 50.175, ...
#> 3 547 POLYGON ((6.016667 50.175, ...
#> 4 535 POLYGON ((6.025 50.175, 6.0...
#> 5 485 POLYGON ((5.966667 50.16667...
#> 6 497 POLYGON ((5.975 50.16667, 5...
#> 7 515 POLYGON ((5.983333 50.16667...
#> 8 515 POLYGON ((5.991667 50.16667...
#> 9 515 POLYGON ((6 50.16667, 6 50....
#> 10 518 POLYGON ((6.008333 50.16667...
plot(sfobj["elevation"], border = NA, nbreaks = 9, pal = terrain.colors)
Created on 2023-04-20 with reprex v2.0.2