代码记录
主客观求指标权重及求城市得分
前言
有22个指标和71个城市的10年数据,现在利用主成分分析法求出客观权重,并结合主管权重得出总权重,最后利用权重与标准化数值求出10年的得分。
前期准备
设置工作路径,读取数据
workL = "C:/Users/goatbishop/Desktop/data"
setwd(workL)
getwd()
library(magrittr)
data <- read.csv("data0710.csv", stringsAsFactors = F)
mendW <- read.table("weight2.txt") %>% c() %>% unlist()
mendW <- mendW/sum(mendW)
方法区
myStand是计算权重用的正向指标标准化化, downStand是计算权重用的负向指标的标准化,upStand2是计算用的正指标标准化方法,upStand2是计算用的负指标标准化方法, weightDemo是提取权重,相当于提取前10个主成分,再进行计算,这里没有依据特征值大小或者累计贡献率提取主成分数,仅仅是较为随意的选取前10个主成分,请注意排查错误!
####方法区####
myStand <- function(x) {
newx = (x-mean(x))/sd(x)
return(newx)
}
downStand <- function(x) {
newx = myStand(-x)
return(newx)
}
upStand2 <- function(x) {
newx = (x-min(x) + 0.01)/(max(x)-min(x))
return(newx)
}
downStand2 <- function(x) {
newx = (max(x)-x + 0.01)/(max(x)-min(x))
return(newx)
}
weightDemo <- function(x) {
#这个问题以后再解决
R <- (t(x) %*% x)/ dim(x)[1]
e <- eigen(R, symmetric=T)
pcMa <- abs(e$vectors)
sqrtValue <- e$values^(0.5)
pcVa <- e$values[1:10]/sum(e$values[1:10])
#print(pcVa)
weightTemp <- t(t(pcMa) / sqrtValue)[, 1:10]
weight <- weightTemp %*% pcVa
weight <- weight/sum(weight)
return(weight)
}
求权重以及得分
构造权重和得分矩阵,并求得权重和得分
#构造权重矩阵
weight <- matrix(0 , ncol = 10, nrow = 22)
colnames(weight) <- c(2018:2009)
weightObj <- matrix(0 , ncol = 10, nrow = 22)
colnames(weightObj) <- c(2018:2009)
#构造得分矩阵
score <- matrix(0 , ncol = 10, nrow = 71)
colnames(score) <- c(2018:2009)
count = 0
for (y in c(2018:2009)) {
count = count + 1
tempdata <- subset(data, year == y)
tempdata = tempdata[, -c(1:3)]
tempData_up <- apply(tempdata[, -c(7, 10, 12, 17, 18)], 2, myStand)
#正向
tempData_down <- apply(tempdata[, c(7, 10, 12, 17, 18)], 2, downStand)
#负向
newData <- cbind(tempData_up, tempData_down)
tempData_up2 <- apply(tempdata[, -c(7, 10, 12, 17, 18)], 2, upStand2 )
tempData_down2 <- apply(tempdata[, c(7, 10, 12, 17, 18)], 2, downStand2)
newData2 <- cbind(tempData_up2, tempData_down2)
## 计算权重
w <- weightDemo(newData)
#print(w)
wave <- (w + mendW)/2
#print(wave)
#列中的所有行加总
weightObj[, count] <- w
weight[, count] <- wave
#print(wave)
##计算得分
s <- newData2 %*% wave
score[, count] <- s
}
rownames(weightObj) <- colnames(newData)
rownames(weight) <- colnames(newData)
rownames(score) <- data[c(1:71), "city"]
写出数据
write.csv(weight, "weightP.csv")
write.csv(weightObj, "weightObj.csv")
write.csv(score, "scoreP.csv")