##
# data <- data.frame(a = runif(10), b = rnorm(10))
# direction <- c(1, -1)
# d1 <- normalize(data, direction = c(1, -1))
# ew1 <- entropyweight(d1)
# ew1

normalize <- function(data, direction){
  data <- data.frame(data)
  k <- which(direction == 1)
  if (length(k) > 0){
    d1 <- data[, k]
    d1 <- data.frame(d1)
    nm1 <- sapply(1:length(k), function(u){
      du <- d1[, u]
      du <- (du - min(du))/(max(du) - min(du))
    })
    data[, k] <- nm1
  }
  
  k <- which(direction == -1)
  if (length(k) > 0){
    d2 <- data[, k]
    d2 <- data.frame(d2)
    nm2 <- sapply(1:length(k), function(u){
      du <- d2[, u]
      du <- (max(du) - du)/(max(du) - min(du))
    })
    data[, k] <- nm2
  }
  
  return(data)
}



entropyweight <- function(data){
  nvar <- ncol(data)
  nobs <- nrow(data)
  ie <- sapply(1:nvar, function(u){
    du <- data[, u]
    du <- du/sum(du)
    -1/(log(nobs))*sum(du * log(du), na.rm = T)
  })
  (1 - ie)/sum(1 - ie)
}

