最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - Writing categorical raster with dbf file does not contain pixel counts - Stack Overflow

programmeradmin3浏览0评论

I am trying to write a rasterize vector file with dbf file using the following code

library(terra)
library(foreign)

f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
plot(v)
r <- rast(system.file("ex/elev.tif", package="terra"))
y <- rasterize(v, r, "NAME_2")

plot(y)

writeRaster(y, filename="Categorical_raster.tif", overwrite=TRUE)
write.dbf(levels(y)[[1]], file = "Categorical_raster.tif.vat.dbf")

But when I am opening the raster file using QGIS, the pixel counts are missing from the raster attribute table.

How do I have the pixel counts in the raster attribute table?

While the attribute table is missing in ArcGIS.

I am trying to write a rasterize vector file with dbf file using the following code

library(terra)
library(foreign)

f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
plot(v)
r <- rast(system.file("ex/elev.tif", package="terra"))
y <- rasterize(v, r, "NAME_2")

plot(y)

writeRaster(y, filename="Categorical_raster.tif", overwrite=TRUE)
write.dbf(levels(y)[[1]], file = "Categorical_raster.tif.vat.dbf")

But when I am opening the raster file using QGIS, the pixel counts are missing from the raster attribute table.

How do I have the pixel counts in the raster attribute table?

While the attribute table is missing in ArcGIS.

Share Improve this question edited yesterday UseR10085 asked yesterday UseR10085UseR10085 8,1884 gold badges32 silver badges68 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You want to add another categorical variable to a SpatRaster. Specifically you want to count the number of raster cells for each category. In that case, you need to compute this, and add it to the categories data.frame. With your example data

library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
r <- rast(system.file("ex/elev.tif", package="terra"))
y <- rasterize(v, r, "NAME_2")

Now get the existing categories, and compute and add the variable of interest. Then save the file to disk with writeRaster.

x <- cats(y)[[1]]
f <- freq(y)
i <- match(f$value, x$NAME_2)
x$cellcount <- f$count[i]
levels(y) <- x
 
out <- writeRaster(y, "test.tif", overwrite=TRUE)

You should not add your own dbf file.

发布评论

评论列表(0)

  1. 暂无评论