问题
Having two rasters (values are floats with 5 decimals) with the same dimensions. The code given below makes one file out of two rasters r and r1. If r is bigger,put blue ,otherwise put red.
This code worked well but I was asked to add another condition. How this code works:
If r is 0.229 and r1 is 0.228 then r is bigger(notice third decimal). what I need is to specify the first two decimals for example:
r= 0.228 r1=0.224 put yellow colour(they are rather similar)
r= 0.238 r1=0.224 put blue colour(r is bigger)
r= 0.128 r1=0.224 put red colour(r is lower)
1- to read the first file r
conn <- file("C:\\corr.bin","rb")
corr<- readBin(conn, numeric(), size=4, n=1440*720, signed=TRUE)
2- to read the second file r1:
conne <- file("C:\\cor06.bin","rb")
over<-readBin(conne, numeric(), size=4, n=1440*720, signed=TRUE)
calculate:
r <-raster(t(matrix((data=corr), ncol=720, nrow=1440)))
r1 <- raster(t(matrix((data=over), ncol=720, nrow=1440)))
m <- r > r1 #Compare the two rasters
image( m , col = c("blue" , "red" ) )
回答1:
You now want to create colours based on if one is greater than the other, or the difference between the two is less than 0.01. You can do this simply like this:
# Example data
r <- raster( system.file("external/test.grd", package="raster") )
r1 <- r * rnorm( ncell(r))
# Make new raster
m <- raster( r )
# 3 = Yellow , 2 = "Red" , 1 = "Blue"
values( m ) <- ifelse( abs( r[] - r1[] ) <= 0.01 , 3 , ifelse( r[] > r1[] , 1 , 2 ) )
image( m , col = c( 1 = "Blue" , 2 = "Red" , 3 = "Yellow" ) )
You can use the value = "colour"
style of argument in col
ensuring colours are assigned to the right levels.
来源:https://stackoverflow.com/questions/15618635/how-to-put-conditions-using-the-decimals-in-calculations