1# Author: Robert J. Hijmans 2# Date: October 2008 3# Version 0.9 4# Licence GPL v3 5 6 7.uniqueNames <- function(x, sep='.') { 8 dups <- unique(x[duplicated(x)]) 9 10 for (dup in dups) { 11 j <- which(x == dup) 12 x[j] <- paste(x[j], sep, 1:length(j), sep='') 13 } 14 15 x 16} 17 18 19.goodNames <- function(ln, prefix='layer') { 20 validNames(ln, prefix) 21} 22 23validNames <- function(x, prefix='layer') { 24 x <- trim(as.character(x)) 25 x[is.na(x)] <- "" 26 if (.standardnames()) { 27 x[x==''] <- prefix 28 x <- make.names(x, unique=FALSE) 29 } 30 .uniqueNames(x) 31} 32 33 34 35 36setMethod('labels', signature(object='Raster'), 37 function(object) { 38 names(object) 39 } 40) 41 42 43setMethod('names', signature(x='Raster'), 44 function(x) { 45 if (.hasSlot(x@data, 'names')) { 46 ln <- x@data@names 47 } else { 48 ln <- x@layernames 49 } 50 ln <- ln[1:nlayers(x)] 51 validNames(as.vector(ln)) 52 } 53) 54 55 56setMethod('names', signature(x='RasterStack'), 57 function(x) { 58 ln <- sapply(x@layers, function(i) i@data@names) 59 ln <- ln[1:nlayers(x)] 60 validNames(as.vector(ln)) 61 } 62) 63 64 65 66 67setMethod('names<-', signature(x='Raster'), 68 function(x, value) { 69 nl <- nlayers(x) 70 if (is.null(value)) { 71 value <- rep('', nl) 72 } else if (length(value) != nl) { 73 stop('incorrect number of layer names') 74 } 75 value <- validNames(value) 76 77 if (inherits(x, 'RasterStack')){ 78 79 x@layers <- sapply(1:nl, function(i){ 80 r <- x@layers[[i]] 81 r@data@names <- value[i] 82 r 83 }) 84 85 } else { 86 if (.hasSlot(x@data, 'names')) { 87 x@data@names <- value 88 } else { 89 x@layernames <- value 90 } 91 } 92 93 return(x) 94 } 95) 96 97