'Renaming variables in raster data using substr

I downloaded worldclimate data and changed it into raster data.

There are names like wc2.1_5m_bio_1 until 19, and I want to rename these variables to bio_1 (start = 10, stop = 16) using substr function. However, I dont know how to make it permanent on the raster data.

substr(clim@ptr[[“names”]], start = 10, stop = 16)

It gives what I want but not permanent. So everytime I reload the raster data, it still has the original long name.



Solution 1:[1]

You can get and set the names like this:

library(terra)
s <- rast(system.file("ex/logo.tif", package="terra"))[[1:2]] 
names(s)
#[1] "red"   "green"

names(s) <- substr(names(s), 1, 1)
names(s)
#[1] "r" "g"

(you should never directly use the @ptr slot)

To make this permanent you need to write the data to a new file:

writeRaster(s, "test.tif", overwrite=TRUE)

rast("test.tif")
#class       : SpatRaster 
#dimensions  : 77, 101, 2  (nrow, ncol, nlyr)
#resolution  : 1, 1  (x, y)
#extent      : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs 
#source      : test.tif 
#names       :   r,   g 
#min values  :   0,   0 
#max values  : 255, 255 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robert Hijmans