Data<-read.csv("C:\\Users\\wataru\\Desktop\\jitaku.csv",header=T)

sample<-nrow(Data)
print(sample)
choice<-3
th0<-c(0,0,0,0,0,0)

fn<-function(x){
th1<-x[1]
th2<-x[2]
th3<-x[3]
th4<-x[4]
th5<-x[5]
th6<-x[6]



LL=0

dt1<-th1*Data[,2]+th2*Data[,3]+th3*Data[,13]+th5*matrix(1,nrow=sample,ncol=1)
dt2<-th1*Data[,5]+th2*Data[,6]+th4*Data[,17]+th6*matrix(1,nrow=sample,ncol=1)
dt3<-th1*Data[,8]+th3*Data[,13]+th4*Data[,17]

Pdt1<-exp(dt1)/(exp(dt1)+exp(dt2)+exp(dt3))
Pdt2<-exp(dt2)/(exp(dt1)+exp(dt2)+exp(dt3))
Pdt3<-exp(dt3)/(exp(dt1)+exp(dt2)+exp(dt3))

CHdt1<-Data[,1]==1
CHdt2<-Data[,1]==2
CHdt3<-Data[,1]==3

LL<-colSums(CHdt1*log(Pdt1)+CHdt2*log(Pdt2)+CHdt3*log(Pdt3))
}

MLE<-optim(th0,fn,method="BFGS",hessian=TRUE,control=list(fnscale=-1))

th<-MLE$par
hes<-MLE$hessian

tval<-th/sqrt(-diag(solve(hes)))

L0<-sample*log(1/choice)

LL<-MLE$value

print((L0-LL)/L0)

print(((sample-length(th))/sample)*((L0-LL)/L0))

print(tval)

print(MLE)

print(L0)

print(LL)
