Search code examples
rrasterterra

How to add calculated columns to a rast or raster


I need to manipulate the below raster by adding new calculated columns to it. I converted the raster to data.frame and added the columns. Question: Is this how I can add columns to a raster by converting to data.frame or I can add columns directly to the raster and save it? Consider the dummy example below:

library(terra)

# Mock data
f <- system.file("extdata/asia.tif", package = "tidyterra")
xx <- rast(f)

rast_df <- as.data.frame(xx,na.rm=TRUE, cells = TRUE)
head(rast_df)

rast_df$col1 <- with(rast_df,cell*5)
rast_df$col2 <- with(rast_df,cell*20)
rast_df$col3 <- with(rast_df,cell*50)

How can I save these new added columns to the original xx rast? I will be adding at least 20 columns to the xx rast.


Solution

  • If you want to add new columns to your raster, you have to change the dimension of your raster:

    dim(xx)
    

    [1] 232 432 1

    dim(xx) <- c(232,433,1) # one column added
    

    Then you can perfom calculations on that new column by

    xx[,433] <- xx[,1]*5 # silly example
    

    But beware that this changes the resolution of your raster.