Skip to content
Prev 20370 / 29559 Next

rasterVis levelplot: Use colortable in raster with attribute table

Thanks for your reply, Oscar,

I'm sorry if the code appears somewhat confusing so I try to explain what it is supposed to do.

So if I use the example from the ratify function help:

r <- raster(nrow=10, ncol=10)
r[] = 1
r[51:100] = 2
r[3:6, 1:5] = 3
r <- ratify(r)

rat <- levels(r)[[1]]
rat$landcover <- c('Pine', 'Oak', 'Meadow')
rat$code <- c(12,25,30)
levels(r) <- rat

cols=c("red","green","blue")

levelplot(r,col.regions=cols)


everything works fine as expected.

So I will try to explain what my code is supposed to do. I have a thematic raster with attribute table. The raster takes on values between 1 and 28 each value representing one class. The value and corresponding class name are stored in the attribute tables column 5 and 4, respectively.

#First I load the raster with the attribute table and color table

r<-raster(##some raster with attribute and colortable##))

#then I create a data frame from the levels of the thematic raster

ratdf<-as.data.frame(levels(r))


#now I extract column 5 of the RAT df which holds the IDs

rat<-as.data.frame(ratdf[[5]])

#Next step: create a vector with the classnames from RAT df col 4

nvec<-as.character(ratdf[[4]])

#then join the class names vector with the ID data frame 

rat$classes<-nvec

#assign the column names of rat 
names(rat)<-c("ID","classes")

#create an empty raster r1 from the r template

r1<-raster(r)

#assign the values of r to r1

r1[]<-r[]

#make a thematic raster of r1
 
r1<-ratify(r1)

#assign the levels to r1 from rat

levels(r1)<-rat


#next steps are to create a color ramp with only the valid colors (since the original raster is 8 bit it could contain up to 256 #colors but I only need colors 2 to 29) and plot the thing

cols<-r at legend@colortable
cols<-cols[2:29]

levelplot(r1,col.regions=cols)

####


What puzzles me is that after I created the new thematic raster with ratify, and I call the raster, it is displayed but under attributes appears the error: Error in 1:ncol(r) : argument of length 0. Maybe this has something to do with the problems plotting that raster. Btw, the same error appears as well when I use as.factor instead of ratify...

Cheers

greg