I added a new variable to code the cells of my shape file, I want to save that file as a .tif
and have all the information of my new variable. I saved it as a new .shp
file and then use shp2raster
function but I get and error.
beijing10<-sf::read_sf("Landuse/Beijing2010.shp")
beijing10<-mutate(beijing10,land=ifelse(CODE%in%c(41,42),"Cultivated Land","Unused Land"))
st_write(beijing10,"beijing2010new.shp")
shp2raster("beijing2010new.shp",column = "land")
error:
Error in p$rasterize(nrow(r), ncol(r), as.vector(extent(r)), values, background) : Not compatible with requested type: [type=character; target=double].
I also try this but I don't get 2 clases.
r <- raster(ncol=180, nrow=180) #can take any value
extent(r) <- extent(beijing10)
rr<-rasterize(beijing10,r,'land')
writeRaster(rr,"beijing2.tif",options=c('TFW=YES'),'land')
Is there a another option to get the .tif
file. Can someone help me to understand how does the transformation work and how should I add the right code so I don't need to use ArcMap do get the file. Thank you
Here is a minimal, reproducible, self-contained example
library(raster)
p <- shapefile(system.file("external/lux.shp", package="raster"))
r <- raster(p, res=0.01)
p$land <- ifelse(p$ID_2 > 6, "Cultivated Land", "Unused Land")
The error occurs because you are trying to rasterize a character variable. That is not supported. You can use a factor, though
p$land <- as.factor(p$land)
r <- rasterize(p, r, "land")
r
#class : RasterLayer
#dimensions : 73, 78, 5694 (nrow, ncol, ncell)
#resolution : 0.01, 0.01 (x, y)
#extent : 5.74414, 6.52414, 49.45162, 50.18162 (xmin, xmax, ymin, ymax)
#crs : +proj=longlat +datum=WGS84 +no_defs
#source : memory
#names : layer
#values : 1, 2 (min, max)