R/create.index.matrix.R

Defines functions create.index.matrix

create.index.matrix <- function(dnames, arr = NULL){
  ndim <- length(dnames)
  
  #if an array was given, then turn dnames into a list of numbers, according to their appearance in arr:
  if(!is.null(arr)){
    dnames.tmp <- dnames
    for(i in 1:ndim){
      dnames.tmp[[i]] <- match(dnames[[i]], dimnames(arr)[[i]], nomatch=0)
    }
    dnames <- dnames.tmp
  }
    
  for(i in 1:ndim) {
    len <- length(dnames[[i]])	#length of current dimension
          	#at first dimension, just write the dimnames as a column into the id.matrix
  	if(i==1) {
      			id.matrix <- as.matrix(dnames[[i]])
    } else {
  	  #for all other dimensions, duplicate each column of the id.matrix as many times as is the length of the new dimension
  		id.matrix.tmp <- NULL
      for(j in 1:len)
  			id.matrix.tmp <- rbind(id.matrix.tmp, id.matrix)
  		
  		#now add the new dimnames as next column:
  		id.matrix <- cbind(id.matrix.tmp, rep(dnames[[i]], each = length(id.matrix[,1])))
  	}
  }
  dimnames(id.matrix)[[2]] <- names(dnames)
  return(id.matrix)
}
############################################# finish create.index.matrix  ##########################################################
pik-piam/nitrogen documentation built on Nov. 5, 2019, 12:48 a.m.