R starter
R starter

Reputation: 197

How to run different formula on different layers in R

I downloaded worlclim/BIO climatic data which has 16 layers. 1-11 layers of which are temperature data. Rests are precipitation data. When I checked document, I should convert unit of temperature data by different conversion factors. 1-2,4-11 layers should be divided by 10 to convert degree celcius and 3-4 layers by 100. To do this, I wrote following code:

 temp1<-clim[[1:2]]/10
 temp2 <-clim[[5:11]]/10
 temp3<-clim[[3:4]]/100

 Stack them back according to the same order as they were in original data:
 clim <-stack(temp1,temp3,temp2)

My question is how to calculate different formula on different layer and stack them back to original order? I want to know another way to do these steps.

Thank you!

Upvotes: 0

Views: 53

Answers (1)

lbusett
lbusett

Reputation: 5932

Easist way could be to define a vector of "dividing factors" and then simply divide the stack by that vector. In this way, you do not need to put the bands in the "original" order:

library(raster)
a <- raster::raster(ncols = 10, nrows = 10)
a <- raster::init(a, runif)

# create a stack
b <- raster::stack(a,a,a,a,a,a)

# define vector of dividing factors
divs <- c(1,1,10,10,100,100)

# compute
c <- b / divs
c
class       : RasterBrick 
dimensions  : 10, 10, 100, 6  (nrow, ncol, ncell, nlayers)
resolution  : 36, 18  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
data source : in memory
names       :      layer.1,      layer.2,      layer.3,      layer.4,      layer.5,      layer.6 
min values  : 5.919103e-03, 5.919103e-03, 5.919103e-04, 5.919103e-04, 5.919103e-05, 5.919103e-05 
max values  :   0.99532098,   0.99532098,   0.09953210,   0.09953210,   0.00995321,   0.00995321 

Upvotes: 1

Related Questions