content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' @title Auxiliary function for the log-likelihood estimation of GeCUB models.
#' @aliases Qunogecub
#' @description Define the opposite one of the two scalar functions that are maximized when running the E-M algorithm
#' for GeCUB models with covariates for feeling, uncertainty and overdispersion.
#' @keywords internal
#' @usage Qunogecub(param,datiuno,s)
#' @param param Vector of initial estimates of parameters for the uncertainty component
#' @param datiuno Auxiliary matrix
#' @param s Number of covariates to explain the shelter effect
Qunogecub<-function(param,datiuno,s){
p<-NROW(param)-s-2;
omega<-param[1:(s+1)];
bet<-param[(s+2):(p+s+2)];
tauno<-datiuno[,1];
taudue<-datiuno[,2];
covar<-datiuno[,3:(s+p+2)];
X<-covar[,1:s]; Y=covar[,(s+1):(s+p)];
alpha1<-logis(X,omega);
alpha2<-(1-alpha1)*logis(Y,bet);
esse1<-sum(tauno*log(alpha1));
esse2<- sum(taudue*log(alpha2));
esse3<- sum((1-tauno-taudue)*log(1-alpha1-alpha2))
return(-esse1-esse2-esse3);
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/Qunogecub.R
|
#' @title Auxiliary matrix
#' @description Returns an auxiliary matrix needed for computing the variance-covariance matrix of a CUBE model with covariates.
#' @aliases auxmat
#' @usage auxmat(m, vettcsi, vettphi, a, b, c, d, e)
#' @param m Number of ordinal categories
#' @param vettcsi Vector of the feeling parameters of the Beta-Binomial distribution, with length equal to the number of observations
#' @param vettphi Vector of the overdispersion parameters of the Beta-Binomial distribution, with length equal to the number of observations
#' @param a Real number
#' @param b Real number
#' @param c Real number
#' @param d Real number
#' @param e Real number
#' @keywords internal
#' @references
#' Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{ Communications in Statistics- Theory and Methods}, \bold{43}, 771--786 \cr
#' Piccolo, D. (2014). Inferential issues on CUBE models with covariates,
#' \emph{Communications in Statistics. Theory and Methods}, \bold{44}, DOI: 10.1080/03610926.2013.821487
auxmat <-
function(m,vettcsi,vettphi,a,b,c,d,e){
elemat<-matrix(NA,nrow=m,ncol=length(vettcsi))
for(k in 1:m){
elemat[k,]<-e*((k-1)^d)/((a+b*vettcsi+vettphi*(k-1))^c)
}
return(elemat)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/auxmat.R
|
#' @title Beta-Binomial probabilities of ordinal responses, with feeling and overdispersion parameters
#' for each observation
#' @description Compute the Beta-Binomial probabilities of ordinal responses, given feeling and overdispersion
#' parameters for each observation.
#' @aliases betabinomial
#' @usage betabinomial(m,ordinal,csivett,phivett)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses. Missing values are not allowed: they should be preliminarily deleted
#' or imputed
#' @param csivett Vector of feeling parameters of the Beta-Binomial distribution for given ordinal responses
#' @param phivett Vector of overdispersion parameters of the Beta-Binomial distribution for given ordinal
#' responses
#' @export betabinomial
#' @return A vector of the same length as ordinal, containing the Beta-Binomial probabilities of each observation,
#' for the corresponding feeling and overdispersion parameters.
#' @details The Beta-Binomial distribution is the Binomial distribution in which the probability of success at
#' each trial is random and follows the Beta distribution. It is frequently used in Bayesian
#' statistics, empirical Bayes methods and classical statistics as an overdispersed binomial distribution.
#' @seealso \code{\link{betar}}, \code{\link{betabinomialcsi}}
#' @references Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 \cr
#' Piccolo D. (2015). Inferential issues for CUBE models with covariates.
#' \emph{Communications in Statistics - Theory and Methods}, \bold{44}(23), 771--786.
#' @keywords distribution
#' @examples
#' data(relgoods)
#' m<-10
#' ordinal<-relgoods$Tv
#' age<-2014-relgoods$BirthYear
#' no_na<-na.omit(cbind(ordinal,age))
#' ordinal<-no_na[,1]; age<-no_na[,2]
#' lage<-log(age)-mean(log(age))
#' gama<-c(-0.6, -0.3)
#' csivett<-logis(lage,gama)
#' alpha<-c(-2.3,0.92);
#' ZZ<-cbind(1,lage)
#' phivett<-exp(ZZ%*%alpha)
#' pr<-betabinomial(m,ordinal,csivett,phivett)
#' plot(density(pr))
betabinomial <-
function(m,ordinal,csivett,phivett){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
n<-length(ordinal)
betabin<-rep(NA,n)
for(i in 1:n){
bebeta<-betar(m,csivett[i],phivett[i])
betabin[i]<-bebeta[ordinal[i]]
}
return(betabin)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/betabinomial.R
|
#' @title Beta-Binomial probabilities of ordinal responses, given feeling parameter for each observation
#' @description Compute the Beta-Binomial probabilities of given ordinal responses, with feeling
#' parameter specified for each observation,
#' and with the same overdispersion parameter for all the responses.
#' @aliases betabinomialcsi
#' @usage betabinomialcsi(m,ordinal,csivett,phi)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses. Missing values are not allowed: they should be preliminarily deleted
#' or imputed
#' @param csivett Vector of feeling parameters of the Beta-Binomial distribution for given ordinal
#' responses
#' @param phi Overdispersion parameter of the Beta-Binomial distribution
#' @export betabinomialcsi
#' @return A vector of the same length as ordinal: each entry is the Beta-Binomial probability for the given observation
#' for the corresponding feeling and overdispersion parameters.
#' @seealso \code{\link{betar}}, \code{\link{betabinomial}}
#' @references Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 \cr
#' Piccolo D. (2015). Inferential issues for CUBE models with covariates.
#' \emph{Communications in Statistics - Theory and Methods}, \bold{44}(23), 771--786.
#' @keywords distribution
#' @examples
#' data(relgoods)
#' m<-10
#' ordinal<-relgoods$Tv
#' age<-2014-relgoods$BirthYear
#' no_na<-na.omit(cbind(ordinal,age))
#' ordinal<-no_na[,1]; age<-no_na[,2]
#' lage<-log(age)-mean(log(age))
#' gama<-c(-0.61,-0.31)
#' phi<-0.16
#' csivett<-logis(lage,gama)
#' pr<-betabinomialcsi(m,ordinal,csivett,phi)
#' plot(density(pr))
betabinomialcsi <-function(m,ordinal,csivett,phi){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
n<-length(ordinal)
betabin<-rep(NA,m)
for(i in 1:n){
bebeta<-betar(m,csivett[i],phi)
betabin[i]<-bebeta[ordinal[i]]
}
return(betabin)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/betabinomialcsi.R
|
#' @title Beta-Binomial distribution
#' @description Return the Beta-Binomial distribution with parameters \eqn{m}, \eqn{csi} and \eqn{phi}.
#' @aliases betar
#' @usage betar(m,csi,phi)
#' @param m Number of ordinal categories
#' @param csi Feeling parameter of the Beta-Binomial distribution
#' @param phi Overdispersion parameter of the Beta-Binomial distribution
#' @export betar
#' @return The vector of length \eqn{m} of the Beta-Binomial distribution.
#' @seealso \code{\link{betabinomial}}
#' @references Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786
#' @keywords distribution
#' @examples
#' m<-9
#' csi<-0.8
#' phi<-0.2
#' pr<-betar(m,csi,phi)
#' plot(1:m,pr,type="h", main="Beta-Binomial distribution",xlab="Ordinal categories")
#' points(1:m,pr,pch=19)
betar <-function(m,csi,phi){
betar<-rep(NA,m)
km<-0:(m-2)
betar[1]<-prod(1-(1-csi)/(1+phi*km))
for(r in 1:(m-1)){
betar[r+1]<-betar[r]*((m-r)/r)*((1-csi+phi*(r-1))/(csi+phi*(m-r-1)))
}
return(betar)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/betar.R
|
#' @title Shifted Binomial probabilities of ordinal responses
#' @description Compute the shifted Binomial probabilities of ordinal responses.
#' @aliases bitcsi
#' @usage bitcsi(m,ordinal,csi)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param csi Feeling parameter of the shifted Binomial distribution
#' @export bitcsi
#' @return A vector of the same length as \code{ordinal}, where each entry is the shifted Binomial probability
#' of the corresponding observation.
#' @seealso \code{\link{probcub00}}, \code{\link{probcubp0}}, \code{\link{probcub0q}}
#' @references Piccolo D. (2003). On the moments of a mixture of uniform and shifted binomial random variables,
#' \emph{Quaderni di Statistica}, \bold{5}, 85--104
#' @keywords distribution
#' @examples
#' data(univer)
#' m<-7
#' csi<-0.7
#' ordinal<-univer$informat
#' pr<-bitcsi(m,ordinal,csi)
bitcsi <-function(m,ordinal,csi){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
base<-log(1-csi)-log(csi)
const<-exp(m*log(csi)-log(1-csi))
const*kkk(m,ordinal)*exp(base*ordinal)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/bitcsi.R
|
#' @title Shifted Binomial distribution with covariates
#' @description Return the shifted Binomial probabilities of ordinal responses where the feeling component
#' is explained by covariates via a logistic link.
#' @aliases bitgama
#' @usage bitgama(m,ordinal,W,gama)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of covariates for the feeling component
#' @param gama Vector of parameters for the feeling component, with length equal to
#' NCOL(W)+1 to account for an intercept term (first entry of \code{gama})
#' @export bitgama
#' @return A vector of the same length as \code{ordinal}, where each entry is the shifted Binomial probability for
#' the corresponding observation and feeling value.
#' @seealso \code{\link{logis}}, \code{\link{probcub0q}}, \code{\link{probcubpq}}
#' @keywords distribution
#' @import stats
#' @examples
#' n<-100
#' m<-7
#' W<-sample(c(0,1),n,replace=TRUE)
#' gama<-c(0.2,-0.2)
#' csivett<-logis(W,gama)
#' ordinal<-rbinom(n,m-1,csivett)+1
#' pr<-bitgama(m,ordinal,W,gama)
bitgama <-function(m,ordinal,W,gama){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
W <- as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
ci<- 1/(logis(W,gama))-1
kkk(m,ordinal)*exp((ordinal-1)*log(ci)-(m-1)*log(1+ci))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/bitgama.R
|
#' @title Pearson \eqn{X^2} statistic
#' @description Compute the \eqn{X^2} statistic of Pearson for CUB models with one or two discrete
#' covariates for the feeling component.
#' @aliases chi2cub
#' @usage chi2cub(m,ordinal,W,pai,gama)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of covariates for the feeling component
#' @param pai Uncertainty parameter
#' @param gama Vector of parameters for the feeling component, with length equal to NCOL(W)+1
#' to account for an intercept term (first entry of \code{gama})
#' @export chi2cub
#' @return A list with the following components:
#' \item{df}{Degrees of freedom}
#' \item{chi2}{Value of the Pearson fitting measure}
#' \item{dev}{Deviance indicator}
#' @details No missing value should be present neither
#' for \code{ordinal} nor for covariate matrices: thus, deletion or imputation procedures should be
#' preliminarily run.
#' @keywords htest
#' @references
#' Tutz, G. (2012). \emph{Regression for Categorical Data}, Cambridge University Press, Cambridge
#' @examples
#' data(univer)
#' m<-7
#' pai<-0.3
#' gama<-c(0.1,0.7)
#' ordinal<-univer$informat; W<-univer$gender;
#' pearson<-chi2cub(m,ordinal,W,pai,gama)
#' degfree<-pearson$df
#' statvalue<-pearson$chi2
#' deviance<-pearson$dev
chi2cub <-
function(m,ordinal,W,pai,gama){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
W <- as.matrix(W)
nw<-NCOL(W)
if(nw==1){
chi2cub1cov(m,ordinal,W,pai,gama)
} else if(nw==2) {
chi2cub2cov(m,ordinal,W[,1],W[,2],pai,gama)
} else{
cat("Works only for at most two covariates")
}
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/chi2cub.R
|
#' @title Pearson \eqn{X^2} statistic for CUB models with one discrete covariate for feeling
#' @description Compute the \eqn{X^2} statistic of Pearson for the goodness of fit of a CUB model for ordinal responses, where the feeling parameter
#' is explained via a logistic transform of the only discrete covariate. It groups ratings in
#' classes according to the values of the covariate.
#' @aliases chi2cub1cov
#' @usage chi2cub1cov(m, ordinal, covar, pai, gama)
#' @param m Integer: number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param covar Vector of the selected covariate for explaining the feeling component
#' @param pai Uncertainty parameter
#' @param gama Vector of parameters for the feeling component, with length equal to 2
#' to account for an intercept term (first entry)
#' @return It returns the following results in a list:
#' \item{df}{Number of degrees of freedom}
#' \item{chi2}{Value of the Pearson fitting measure}
#' \item{dev}{Deviance indicator}
#' @keywords internal
#' @import stats
#' @references Tutz, G. (2011). \emph{Regression for categorical data}, Cambridge Series in Statistical
#' and Probabilistic Mathematics
chi2cub1cov <-function(m,ordinal,covar,pai,gama){
covar<-as.matrix(covar)
n<-length(ordinal)
elle<-as.numeric(sort(unique(covar)))
kappa<-length(elle)
matfrel<-matrix(NA,nrow=kappa,ncol=m)
matprob<-matrix(NA,nrow=kappa,ncol=m)
chi2<-0
dev<-0
j<-1
while(j<=kappa){
quali<-which(covar==elle[j])
Wquali<-covar[quali]
qualiord<-ordinal[quali]
nk<- length(qualiord)
matfrel[j,]=tabulate(qualiord,nbins=m)/nk
nonzero<-which(matfrel[j,]!=0)
paij<-pai
csij<-1/(1+ exp(-gama[1]-gama[2]*elle[j]))
matprob[j,]<-t(probcub00(m,paij,csij))
chi2<-chi2+nk*sum(((matfrel[j,]-matprob[j,])^2)/matprob[j,])
dev<- dev + 2*nk*sum(matfrel[j,nonzero]*log(matfrel[j,nonzero]/matprob[j,nonzero]))
j<-j+1
}
df<- kappa*(m-1)-(length(gama)+1)
cat("Degrees of freedom ==> df =",df, "\n")
cat("Pearson Fitting measure ==> X^2 =",chi2,"(p-val.=",1-pchisq(chi2,df),")","\n")
cat("Deviance ==> Dev =",dev,"(p-val.=",1-pchisq(dev,df),")","\n")
results<-list('chi2'=chi2,'df'=df,'dev'=dev)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/chi2cub1cov.R
|
#' @title Pearson \eqn{X^2} statistic for CUB models with one discrete covariate for feeling
#' @description Compute the \eqn{X^2} statistic of Pearson for the goodness of fit of a CUB model for ordinal responses, where the feeling parameter
#' is explained via a logistic transform of the only discrete covariate. It groups ratings in
#' classes according to the values of the covariate.
#' @aliases chi2cub2cov
#' @usage chi2cub2cov(m, ordinal, covar1, covar2, pai, gama)
#' @param m Integer: number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param covar1 Vector of the first covariate values for explaining the feeling component
#' @param covar2 Vector of the second covariate values for explaining the feeling component
#' @param pai Uncertainty parameter
#' @param gama Vector of parameters for the feeling component, with length equal to 2
#' to account for an intercept term (first entry)
#' @return It returns the following results in a list:
#' \item{df}{Number of degrees of freedom}
#' \item{chi2}{Value of the Pearson fitting measure}
#' \item{dev}{Deviance indicator}
#' @keywords internal
#' @import stats
#' @references
#' Tutz, G. (2011). \emph{Regression for categorical data}, Cambridge Series in Statistical
#' and Probabilistic Mathematics
chi2cub2cov <-function(m,ordinal,covar1,covar2,pai,gama){
n<-length(ordinal)
W<-cbind(covar1,covar2)
elle1<-as.numeric(sort(unique(covar1)))
elle2<-as.numeric(sort(unique(covar2)))
profiles<-expand.grid(elle1,elle2)
kappa<-nrow(profiles)
matfrel<-matrix(NA,nrow=kappa,ncol=m)
matprob<-matrix(NA,nrow=kappa,ncol=m)
chi2<-0
dev<-0
j<-1
while(j<=kappa){
quali<-which(covar1==profiles[j,1] & covar2==profiles[j,2])
if (length(quali) == 0){
j<-j+1; print(paste("Profile ",j-1,"is void")); cat("\n") ;
}else {
Wquali<-W[quali,]
qualiord<-ordinal[quali]
nk<- length(qualiord)
matfrel[j,]<-tabulate(qualiord,nbins=m)/nk
nonzero<-which(matfrel[j,]!=0)
paij<-pai
csij<-1/(1+ exp(-gama[1]-gama[2]*profiles[j,1]-gama[3]*profiles[j,2]))
matprob[j,]<-t(probcub00(m,paij,csij))
chi2<-chi2+nk*sum(((matfrel[j,]-matprob[j,])^2)/matprob[j,])
dev<- dev + 2*nk*sum(matfrel[j,nonzero]*log(matfrel[j,nonzero]/matprob[j,nonzero]))
j<-j+1
}
}
df<-kappa*(m-1)-(length(gama)+1)
cat("Degrees of freedom ==> df =",df, "\n")
cat("Pearson Fitting measure ==> X^2 =",chi2,"(p-val.=",1-pchisq(chi2,df),")","\n")
cat("Deviance ==> Dev =",dev,"(p-val.=",1-pchisq(dev,df),")","\n")
results<-list('chi2'=chi2,'df'=df,'dev'=dev)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/chi2cub2cov.R
|
#' @title S3 Method: coef for class "GEM"
#' @description S3 method: coef for objects of class \code{\link{GEM}}.
#' @aliases coef.GEM
#' @method coef GEM
#' @param object An object of class \code{\link{GEM}}
#' @param ... Other arguments
#' @import methods
#' @return ML estimates of parameters of the fitted GEM model.
#' @details Returns estimated values of coefficients of the fitted model
#' @export
#' @rdname coef.GEM
#' @keywords package
#' @seealso \code{\link{GEM}}, \code{\link{summary}}
#coef<- function(object,...) UseMethod("coef", object)
coef.GEM<-function(object,...){
arguments<-list(...)
digits<-arguments$digits
output<-list()
if (is.null(digits)){
digits<-options()$digits
}
ellipsis<-object$ellipsis
listanomi<-parnames(object)
mat<-round(as.matrix(object$estimates),digits=digits)
dimnames(mat)<-list(listanomi,"")
mat
}
#
# ################### prova
#
#
# print.coef.GEM <- function(x,...){
#
# object<-x$object
# family<-object$family
# mat<-x$values
# stime<-object$estimates
#
# listanomi<-parnames(object)
#
# modello<-object$formula
# data<-object$data
#
# mf<-model.frame(modello,data=data,na.action=na.omit)
#
#
# data<-object$data
#
# if ( family == "CUB"){
# covpai<-model.matrix(modello,data=mf,rhs=1)
# covcsi<-model.matrix(modello,data=mf,rhs=2)
# covshe<-model.matrix(modello,data=mf,rhs=3)
#
# if (ncol(covpai)==0){
# Y<-NULL
# } else {
#
# if (NCOL(covpai)==2){
# Y<-as.matrix(covpai[,-1])
# colnames(Y)<-colnames(covpai)[2]
# } else {
# Y<-covcsi[,-1]
# }
# }
# if (ncol(covcsi)==0){
# W<-NULL
# } else {
# if (NCOL(covcsi)==2){
# W<-as.matrix(covcsi[,-1])
# colnames(W)<-colnames(covcsi)[2]
# } else {
# W<-covcsi[,-1]
# }
# }
#
# if (ncol(covshe)==0){
# X<-NULL
# } else {
# X<-covshe[,-1]
# }
#
# if (!is.null(X) & !is.null(Y) & !is.null(W) & !is.null(object$ellipsis$shelter)){
# Y<-as.matrix(Y); W<-as.matrix(W); X<-as.matrix(X);
# p<-NCOL(Y);
# q<-NCOL(W);
# s<-NCOL(X);
#
# mat1<-cbind(mat[1:(p+1),1])
# colnames(mat1)<-c("Estimates")
# rownames(mat1)<-listanomi[1:(p+1)]
#
# mat2<-cbind(mat[(p+2):(p+q+2),1])
# rownames(mat2)<-listanomi[(p+2):(p+q+2)]
#
# mat3<-cbind(mat[(p+q+3):(p+q+s+3),1])
# rownames(mat3)<-listanomi[(p+q+3):(p+q+s+3)]
#
# cat("Uncertainty ", "\n")
#
# print(mat1,digits=digits)
# cat("==================================","\n")
# cat("Feeling ", "\n")
# colnames(mat2)<-c("Estimates")
#
# print(mat2,digits=digits)
# cat("==================================","\n")
#
# cat("Shelter effect ", "\n")
# colnames(mat3)<-"Estimates"
# print(mat3,digits=digits)
#
# } else if (is.null(object$ellipsis$shelter) & is.null(X) & !is.null(Y) & !is.null(W)){
# Y<-as.matrix(Y); W<-as.matrix(W);
# p<-NCOL(Y);
# q<-NCOL(W);
#
# mat1<-as.matrix(mat[1:(p+1),1])
# colnames(mat1)<-c("Estimates")
# rownames(mat1)<-listanomi[1:(p+1)]
#
# mat2<-as.matrix(mat[(p+2):(p+q+2),1])
# rownames(mat2)<-listanomi[(p+2):(p+q+2)]
#
# cat("Uncertainty ", "\n")
#
# print(mat1,digits=digits)
# colnames(mat2)<-c("Estimates")
# cat("==================================","\n")
#
# cat("Feeling ", "\n")
# print(mat2,digits=digits)
#
# } else if (is.null(object$ellipsis$shelter) & is.null(X) & is.null(Y) & !is.null(W)){
# W<-as.matrix(W);
#
# q<-NCOL(W);
#
# mat1<-as.matrix(mat[1,1])
# colnames(mat1)<-c("Estimates")
# rownames(mat1)<-listanomi[1]
#
# mat2<-cbind(mat[2:(q+2),1])
# colnames(mat2)<-c("Estimates")
# rownames(mat2)<-listanomi[2:(q+2)]
#
# cat("Uncertainty ", "\n")
#
# print(mat1,digits=digits)
# cat("==================================","\n")
#
# cat("Feeling ", "\n")
# print(mat2,digits=digits)
#
# } else if (is.null(object$ellipsis$shelter) & is.null(X) & !is.null(Y) & is.null(W)){
# Y<-as.matrix(Y);
#
# p<-NCOL(Y);
#
# mat1<-cbind(mat[1:(p+1),1])
# colnames(mat1)<-c("Estimates")
# rownames(mat1)<-listanomi[1:(p+1)]
#
# mat2<-cbind(mat[(p+2),1])
# rownames(mat2)<-listanomi[p+2]
#
# colnames(mat2)<-c("Estimates")
#
# cat("Uncertainty ", "\n")
#
# print(mat1,digits=digits)
# cat("==================================","\n")
#
# cat("Feeling ", "\n")
# print(mat2,digits=digits)
#
# } else if (is.null(object$ellipsis$shelter) & is.null(X) & is.null(Y) & is.null(W)) {
#
# mat1<-cbind(mat[1])
# colnames(mat1)<-c("Estimates")
# rownames(mat1)<-listanomi[1]
#
#
# mat2<-cbind(mat[2])
# colnames(mat2)<-c("Estimates")
# rownames(mat2)<-listanomi[2]
#
# cat("Uncertainty ", "\n")
#
# print(mat1,digits=digits)
# cat("==================================","\n")
#
# cat("Feeling ", "\n")
# print(mat2,digits=digits)
#
#
# }
# }
#
#
# if (family == "CUBE"){
#
# covpai<-model.matrix(modello,data=mf,rhs=1)
# covcsi<-model.matrix(modello,data=mf,rhs=2)
# covphi<-model.matrix(modello,data=mf,rhs=3)
#
# if (ncol(covpai)==0){
# Y<-NULL
# } else {
# Y<-covpai[,-1]
# }
# if (ncol(covcsi)==0){
# W<-NULL
# } else {
# W<-covcsi[,-1]
# }
# if (ncol(covphi)==0){
# Z<-NULL
# } else {
# Z<-covphi[,-1]
# }
#
# if (is.null(Y)& is.null(W) & is.null(Z)){
# mat1<-cbind(mat[1])
# colnames(mat1)<-c("Estimates")
# rownames(mat1)<-listanomi[1]
#
# mat2<-cbind(mat[2])
# colnames(mat2)<-c("Estimates")
# rownames(mat2)<-listanomi[2]
#
# cat("Uncertainty ", "\n")
#
# print(mat1,digits=digits)
# cat("==================================","\n")
#
# cat("Feeling ", "\n")
# print(mat2,digits=digits)
# cat("==================================","\n")
#
# cat("Overdispersion ", "\n")
#
# mat3<-cbind(mat[3])
# colnames(mat3)<-c("Estimates")
# rownames(mat3)<-listanomi[3]
#
# print(mat3,digits=digits)
# } else if (is.null(Y)& !is.null(W) & is.null(Z)){
#
# q<-NCOL(W)
#
# mat1<-cbind(mat[1])
# colnames(mat1)<-c("Estimates")
# rownames(mat1)<-listanomi[1]
#
# mat2<-cbind(mat[2:(q+2)])
# colnames(mat2)<-c("Estimates")
# rownames(mat2)<-listanomi[2:(q+2)]
#
# cat("Uncertainty ", "\n")
# print(mat1,digits=digits)
#
# cat("==================================","\n")
#
# cat("Feeling ", "\n")
# print(mat2,digits=digits)
# cat("==================================","\n")
#
# cat("Overdispersion ", "\n")
#
# mat3<-cbind(mat[q+3])
# colnames(mat3)<-c("Estimates")
# rownames(mat3)<-listanomi[q+3]
#
# print(mat3,digits=digits)
#
#
# }
# else if (!is.null(Y)& !is.null(W) & !is.null(Z)){
# p<-NCOL(Y)
# q<-NCOL(W)
# s<-NCOL(Z)
#
# mat1<-cbind(mat[1:(p+1)])
# mat2<-cbind(mat[(2+p):(q+p+2)])
# colnames(mat1)<-colnames(mat2)<-c("Estimates")
# rownames(mat1)<-listanomi[1:(p+1)]
# rownames(mat2)<-listanomi[(2+p):(q+p+2)]
#
#
# cat("Uncertainty ", "\n")
# print(mat1,digits=digits)
#
# cat("==================================","\n")
#
# cat("Feeling ", "\n")
# print(mat2,digits=digits)
# cat("==================================","\n")
#
# cat("Overdispersion ", "\n")
#
# mat3<-cbind(mat[(p+q+3):(p+q+s+3)])
# rownames(mat2)<-listanomi[(p+q+3):(p+q+s+3)]
#
# colnames(mat3)<-c("Estimates")
# print(mat3,digits=digits)
#
#
# }
#
#
# }
#
#
# if (family == "IHG" | family =="CUSH"){
# matout<-mat
#
# colnames(matout)<-c("Estimates")
# print(matout,digits=digits)
# }
#
#
#
# # cat("==================================","\n")
# if (family=="CUB" & !is.null(object$ellipsis$shelter)){
# covshe<-model.matrix(modello,data=mf,rhs=3)
#
# if (ncol(covshe)==0){
# X<-NULL
# } else {
# X<-covshe[,-1]
# }
#
#
# if (is.null(X)){
# matout<-mat
#
# colnames(matout)<-c("Estimates")
# print(matout,digits=digits)
# pai1<-stime[1];pai2<-stime[2];csi<-stime[3]
# delta<-1-pai1-pai2
# paistar<-pai1/(pai1+pai2)
# stime2<-c(paistar,csi,delta)
# nomi2<-c("paistar","csi","delta")
#
# mat2<-as.matrix(stime2)
# matout2<-mat2
# dimnames(matout2)<-list(nomi2,c("Estimates"))
#
#
# cat("==================================","\n")
# cat("Alternative parameterization","\n")
# print(matout2,digits=digits)
# cat("==================================","\n")
# }
# }
#
#
# }
# print(output)
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/coef.R
|
#' @title Correlation matrix for estimated model
#' @description Compute parameter correlation matrix for estimated model as returned by an object
#' of class "GEM".
#' @aliases cormat
#' @usage cormat(object,digits=options()$digits)
#' @param object An object of class "GEM"
#' @param digits Number of significant digits to be printed. Default is \code{options()$digits}
#' @export
#' @return Parameters correlation matrix for fitted GEM models.
#' @keywords models
#' @seealso \code{GEM}, \code{vcov}
cormat<-function(object,digits=options()$digits){
varmat<-vcov(object)
np<-NROW(varmat)
cormat<-diag(rep(1,np))
if (np>1){
if (isTRUE(varmat==matrix(NA,nrow=np,ncol=np))==TRUE){
cormat<-matrix(NA,nrow=np,ncol=np)
dimnames(cormat)<-list(parnames(object),parnames(object))
} else {
ddd<-diag(sqrt(1/diag(varmat)))
cormat<-round(ddd%*%varmat%*%ddd,digits)
dimnames(cormat)<-list(parnames(object),parnames(object))
}
} else {
dimnames(cormat)<-list(parnames(object),"Correlation")
}
return(cormat)
}
#
# cormat <- function(object) UseMethod("cormat", object)
#
#
# cormat.GEM<-function(object){
#
# if(!inherits(object, "GEM")) stop("not a \"GEM\" fit")
#
#
# varmat<-vcov(object)
# np<-NROW(varmat)
# cormat<-diag(rep(1,np))
#
# if (np>1){
# if (isTRUE(varmat==matrix(NA,nrow=np,ncol=np))==TRUE){
# cormat<-matrix(NA,nrow=np,ncol=np)
# dimnames(cormat)<-list(parnames(object),parnames(object))
#
# } else {
# ddd<-diag(sqrt(1/diag(varmat)))
# cormat<-round(ddd%*%varmat%*%ddd,5)
# dimnames(cormat)<-list(parnames(object),parnames(object))
#
# }
#
# } else {
# dimnames(cormat)<-list(parnames(object),"Correlation")
# }
#
# return(cormat)
# }
#
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cormat.R
|
#' @title Main function for CUB models without covariates
#' @description Function to estimate and validate a CUB model without covariates for given ordinal responses.
#' @aliases cub00
#' @usage cub00(m, ordinal, maxiter, toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @return An object of the class "CUB"
#' @seealso \code{\link{CUB}}, \code{\link{probbit}}, \code{\link{probcub00}}, \code{\link{loglikCUB}}
#' @keywords internal
#' @import stats graphics
cub00<-function(m,ordinal,maxiter,toler){
tt0<-proc.time()
serie<-1:m
freq<-tabulate(ordinal,nbins=m)
n<-sum(freq)
aver<-mean(ordinal); varcamp<-mean(ordinal^2)-aver^2;
#######################################################
inipaicsi<-inibest(m,freq); pai<-inipaicsi[1]; csi<-inipaicsi[2];
##################################################################
loglik<-loglikcub00(m,freq,pai,csi)
# ********************************************************************
# ************* E-M algorithm for CUB(0,0) ***************************
# ********************************************************************
nniter<-1
while(nniter<=maxiter){
likold<-loglik
bb<-probbit(m,csi)
aa<-(1-pai)/(m*pai*bb)
tau<-1/(1+aa)
ft<-freq*tau
averpo<-(t(serie)%*%ft)/sum(ft)
pai<-(t(freq)%*%tau)/n # updated pai estimate
csi<-(m-averpo)/(m-1) # updated csi estimate
if(csi<0.001){
csi<-0.001;nniter<-maxiter-1;
}
# print(c(pai,csi));
loglik<-loglikcub00(m,freq,pai,csi)
liknew<-loglik
testll<-abs(liknew-likold) ###### print(testll);
# OPTIONAL printing: print(cbind(nniter,testll,pai,csi));
if(testll<=toler) break else {loglik<-liknew}
# OPTIONAL printing: print(loglik);
nniter<-nniter+1
}
######
if(csi>0.999) csi<-0.99
if(csi<0.001) csi<-0.01 ### to avoid division by 0 !!!
if(pai<0.001) pai<-0.01 ### to avoid division by 0 !!!
### to ensure identifiability !!!
######
AICCUB00<- -2*loglik+2*(2)
BICCUB00<- -2*loglik+log(n)*(2)
nomi<-rbind("pai","csi");stime<-round(c(pai,csi),5);
###############################
theorpr<-probcub00(m,pai,csi)
dissimi<-dissim(theorpr,freq/n)
pearson<-((freq-n*theorpr))/sqrt(n*theorpr)
X2<-sum(pearson^2)
relares<-(freq/n-theorpr)/theorpr
llunif<- -n*log(m); csisb<-(m-aver)/(m-1);
llsb<-loglikcub00(m,freq,1,csisb)
nonzero<-which(freq!=0)
logsat <- -n*log(n)+sum((freq[nonzero])*log(freq[nonzero]))
devian<-2*(logsat-loglik)
LL2<-1/(1+mean((freq/(n*theorpr)-1)^2))
II2<-(loglik-llunif)/(logsat-llunif)
FF2<-1-dissimi
mat1<-cbind(pai,csi,loglik,n,X2,dissimi)
expcub<-expcub00(m,pai,csi); varcub<-varcub00(m,pai,csi);
varmat<-varcovcub00(m,ordinal,pai,csi)
### Computation of var-covar of estimates,
if (isTRUE(varmat==matrix(NA,nrow=2,ncol=2))==TRUE){
ddd<-matrix(NA,nrow=2,ncol=2)
trvarmat<-ICOMP<-NA
errstd<-wald<-pval<-rep(NA,2)
} else {
ddd<-diag(sqrt(1/diag(varmat)))
nparam<-length(stime)
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
errstd<-sqrt(diag(varmat));wald<-stime/errstd;
pval<-2*(1-pnorm(abs(wald)))
cormat<-ddd%*%varmat%*%ddd
esq<-sqrt(varmat[1,1])/m
}
####################################################################
# Print CUB(0,0) results of ML estimation
# rdiss00<-round(dissimi,3)
stampa<-cbind(1:m,freq/n,theorpr,pearson,relares)
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'=stime,'ordinal'=ordinal,'time'=durata,
'loglik'=loglik,'niter'=nniter,
'varmat'=varmat,'BIC'=BICCUB00)
#class(results)<-"cub"
return(results)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cub00.R
|
#' @title Main function for CUB models with covariates for the feeling component
#' @description Function to estimate and validate a CUB model for given ordinal responses, with covariates for
#' explaining the feeling component.
#' @aliases cub0q
#' @usage cub0q(m, ordinal, W, maxiter, toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of selected covariates for explaining the feeling component, not including intercept
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @import stats graphics
#' @return An object of the class "CUB"
#' @references
#' Piccolo D. and D'Elia A. (2008), A new approach for modelling consumers' preferences,
#' \emph{Food Quality and Preference}, \bold{18}, 247--259 \cr
#' @references
#' Iannario M. and Piccolo D. (2010), A new statistical model for the analysis of customer
#' satisfaction, #' \emph{Quality Technology and Quantity management}, \bold{7}(2) 149--168 \cr
#' Iannario M. and Piccolo D. (2012), CUB models: Statistical methods and empirical evidence, in:
#' Kenett R. S. and Salini S. (eds.), \emph{Modern Analysis of Customer Surveys: with applications using R},
#' J. Wiley and Sons, Chichester, 231--258.
#' @keywords internal
cub0q<-function(m,ordinal,W,maxiter,toler){
tt0<-proc.time()
n<-length(ordinal)
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
q<-NCOL(W)
aver<-mean(ordinal)
WW<-cbind(1,W)
##############################################################
freq<-tabulate(ordinal,nbins=m); inipaicsi<-inibest(m,freq); paijj<-inipaicsi[1];
gamajj<-inibestgama(m,ordinal,W)
##############################################################
loglikjj<-loglikcub0q(m,ordinal,W,paijj,gamajj)
# ********************************************************************
# ************* E-M algorithm for CUB(0,q) ***************************
# ********************************************************************
nniter<-1
while(nniter<=maxiter){
loglikold<-loglikjj
vettn<-bitgama(m,ordinal,W,gamajj)
ttau<-1/(1+(1-paijj)/(m*paijj*vettn))
################################# maximize w.r.t. gama ########
ordd<-ordinal;covar<-WW;
gama<-gamajj
optimgama<-optim(gama,effe01,esterno01=cbind(ttau,ordinal,WW),m=m)
################################################################
gamajj<-optimgama$par
paijj<-sum(ttau)/n #updated pai estimate
loglikjj<-loglikcub0q(m,ordinal,W,paijj,gamajj)## needed for nlm version
# print(c(nniter,paijj,gamajj,loglikjj)); #OPTIONAL PRINTING OF ITERATIONS
testll<-abs(loglikjj-loglikold)
if(testll<=toler) break else {loglikold<-loglikjj}
nniter<-nniter+1
}
pai<-paijj; gama<-gamajj; loglik<-loglikjj;
####################################################################
AICCUB0q<- -2*loglik+2*(q+2)
BICCUB0q<- -2*loglik+log(n)*(q+2)
####################################################################
# Compute asymptotic standard errors of ML estimates
####################################################################
varmat<-varcovcub0q(m,ordinal,W,pai,gama)
nomi<-c("pai ",paste("gamma",0:(length(gama)-1),sep="_"))
stime<-c(pai,gama)
nparam<-length(stime)
if (isTRUE(varmat==matrix(NA,nrow=nparam,ncol=nparam))==TRUE){
ddd<-cormat<-matrix(NA,nrow=nparam,ncol=nparam)
ICOMP<-trvarmat<-NA
errstd<-wald<-pval<-rep(NA,nparam)
} else {
ddd<-diag(sqrt(1/diag(varmat)))
cormat<-(ddd%*%varmat)%*%ddd
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat)) ## added
errstd<-sqrt(diag(varmat)); wald<-stime/errstd;
pval<-2*(1-pnorm(abs(wald)))
}
rownames(cormat)<-nomi;colnames(cormat)<-nomi;
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'=stime,'ordinal'=ordinal,'time'=durata,
'loglik'=loglik,'niter'=nniter,'varmat'=varmat,
'BIC'=BICCUB0q)
# class(results)<-"cub"
return(results)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cub0q.R
|
#' @title Main function for CUBE models without covariates
#' @description Estimate and validate a CUBE model without covariates.
#' @aliases cube000
#' @usage cube000(m, ordinal, starting, maxiter, toler, expinform)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param starting Vector of initial estimates to start the optimization algorithm,
#' whose length equals the number of parameters of the model
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @param expinform Logical: if TRUE, the function returns the expected variance-covariance matrix
#' @return An object of the class "CUBE"
#' @import stats
#' @references
#' Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 \cr
#' Iannario, M. (2015). Detecting latent components in ordinal data with overdispersion by means
#' of a mixture distribution, \emph{Quality & Quantity}, \bold{49}, 977--987
#' @keywords internal #models
cube000<-function(m,ordinal,starting,maxiter,
toler,expinform){ #default for expinform = FALSE
tt0<-proc.time()
freq<-tabulate(ordinal,nbins=m); n<-sum(freq);
aver<-mean(ordinal); varcamp<-mean(ordinal^2)-aver^2;
########################################################
#(00)# initial estimates, not efficient:
#starting<-inibestcube(m,ordinal)
pai<-starting[1]; csi<-starting[2]; phi<-starting[3];
#(0)# log-lik
loglik<-loglikcube(m,freq,pai,csi,phi)
# ********************************************************************
# ************* E-M algorithm for CUBE *************************
# ********************************************************************
nniter<-1
while(nniter<=maxiter){
likold<-loglik
#(1)# betar
bb<-betar(m,csi,phi)
aa<-(1-pai)/(m*pai*bb)
#(2)# taunor
tauno<-1/(1+aa)
#(3)# pai(k+1)
pai<-sum(freq*tauno)/n # updated pai estimate
paravecjj<-c(csi,phi)
#(4)# Q(k+1)
dati<-cbind(tauno,freq)
################ EFFECUBE is Q(csi,phi) ###########################
#(5)# (csi(k+1),phi(k+1))
################################## maximize w.r.t. paravec ########
paravec<-paravecjj
optimestim<-optim(paravec,effecube,dati=dati,m=m,method = "L-BFGS-B",lower=c(0.01,0.01),upper=c(0.99,0.3)) # print(nlmaxg)
################################################################
#(6)# theta(k+1)
paravecjj<-optimestim$par # updated paravec estimates
csi<-paravecjj[1]; phi<-paravecjj[2];
##########################################
if(pai<0.001){pai<-0.001; nniter<-maxiter-1}
#if(csi<0.001){csi<-0.001; nniter<-maxiter-1}
#if(phi<0.001){phi<-0.001; nniter<-maxiter-1}
if(pai>0.999){pai<-0.99} ### to avoid division by 0 !!!
#if(csi>0.999){csi<-0.99} ### to avoid division by 0 !!!
###################################### print(c(nniter,pai,csi,phi));
#(7)# elle(theta(k+1))
liknew<-loglikcube(m,freq,pai,csi,phi)
#(8)# test
testll<-abs(liknew-likold) # OPTIONAL printing: print(testll);
# OPTIONAL printing: print(cbind(nniter,testll,pai,csi,phi));
if(testll<=toler) break else {loglik<-liknew} # OPTIONAL printing: print(loglik);
nniter<-nniter+1
}
loglik<-liknew
###### End of E-M algorithm for CUBE ***********************************************
AICCUBE<- -2*loglik+2*(3)
BICCUBE<- -2*loglik+log(n)*(3)
# ********************************************************
# Compute ML var-cov matrix and print result for CUBE
# ********************************************************
if(expinform==TRUE){
varmat<-varcovcubeexp(m,pai,csi,phi,n)
}
else{
varmat<-varcovcubeobs(m,pai,csi,phi,freq)
}
# nomi<-rbind("pai ","csi ","phi ")
stime<-c(pai,csi,phi)
nparam<-length(stime)
if (isTRUE(varmat==matrix(NA,nrow=nparam,ncol=nparam))==TRUE){
ddd<-matrix(NA,nrow=nparam,ncol=nparam)
trvarmat<-ICOMP<-NA
errstd<-wald<-pval<-rep(NA,nparam)
} else {
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
errstd<-sqrt(diag(varmat))
wald<-stime/errstd
pval<-2*(1-pnorm(abs(wald)))
ddd<-diag(sqrt(1/diag(varmat)))
}
####################################################################
# Print CUBE results of ML estimation
####################################################################
### Log-likelihood comparisons ##############################################
llunif<- -n*log(m)
csisb<-(m-aver)/(m-1)
llsb<-loglikcub00(m,freq,1,csisb)
nonzero<-which(freq!=0)
logsat<- -n*log(n)+sum((freq[nonzero])*log(freq[nonzero]))
devian<-2*(logsat-loglik)
theorpr<-probcube(m,pai,csi,phi)
dissimcube<-dissim(theorpr,freq/n)
pearson<-((freq-n*theorpr))/sqrt(n*theorpr)
X2<-sum(pearson^2)
relares<-(freq/n-theorpr)/theorpr
FF2<-1-dissimcube
LL2<-1/(1+mean((freq/(n*theorpr)-1)^2))
II2<-(loglik-llunif)/(logsat-llunif)
stampa<-cbind(1:m,freq/n,theorpr,pearson,relares)
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'= stime, 'loglik'= loglik,
'niter'= nniter, 'varmat'= varmat,'BIC'=BICCUBE,'time'=durata)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cube000.R
|
#' @title Main function for CUBE models with covariates
#' @description Function to estimate and validate a CUBE model with
#' explicative covariates for all the three parameters.
#' @aliases cubecov
#' @keywords internal
#' @usage cubecov(m, ordinal, Y, W, Z, starting, maxiter, toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates for explaining the uncertainty component
#' @param W Matrix of selected covariates for explaining the feeling component
#' @param Z Matrix of selected covariates for explaining the overdispersion component
#' @param starting Vector of initial parameters estimates to start the optimization algorithm
#' (it has length NCOL(Y) + NCOL(W) + NCOL(Z) + 3 to account for intercept terms
#' for all the three components
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @return An object of the class "CUBE"
#' @import stats
#' @references
#' Piccolo, D. (2014). Inferential issues on CUBE models with covariates,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{44},
#' DOI: 10.1080/03610926.2013.821487
cubecov<-function(m,ordinal,Y,W,Z,starting,maxiter,toler){
tt0<-proc.time()
n<-length(ordinal)
Y<-as.matrix(Y); W<-as.matrix(W); Z<-as.matrix(Z);
p<-NCOL(Y)
q<-NCOL(W)
v<-NCOL(Z)
aver<-mean(ordinal)
if (ncol(W)==1){
W<-as.numeric(W)
}
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(Z)==1){
Z<-as.numeric(Z)
}
YY<-cbind(1,Y)
WW<-cbind(1,W)
ZZ<-cbind(1,Z)
# **********************************
# *** E-M algorithm for CUBECOV ***
# **********************************
#################################################################
# 00.# Initial values of parameters ............. Attention !!! #
#################################################################
betjj<-starting[1:(p+1)]
gamajj<-starting[(p+2):(p+q+2)]
alphajj<-starting[(p+q+3):(p+q+v+3)]
################################
# * * * Iterative Loop * * *#
################################
nniter<-1
while(nniter<=maxiter){
#################################################################
# 01.# Initial values of vectors i=1,2,..,n
#################################################################
paijj<-logis(Y,betjj); csijj<-logis(W,gamajj)
phijj<-1/(1/logis(Z,alphajj)-1) #****
#################################################################
# 02.# Computation of beta-binomial distribution i=1,2,..,n
#################################################################
betabin<-betabinomial(m,factor(ordinal,ordered=TRUE),csijj,phijj)
#################################################################
# 03.# Computation of CUBE probability distribution i=1,2,..,n
#################################################################
probi<-paijj*(betabin-1/m)+1/m
likold<-sum(log(probi))
#################################################################
# 4.# Computation of conditional probability i=1,2,..,n
#################################################################
taui<-1-(1-paijj)/(m*probi)
#################################################################
# 5. Unify parameter vectors
param<-c(gamajj,alphajj)
#################################################################
# 6.# Maximization of Q_1(beta) and Q_2(param)
#################################################################
### maximize w.r.t. bet and gama #########
esterno1<-cbind(taui,YY)
covar<-esterno1[,2:NCOL(esterno1)]
esterno2<-cbind(taui,ordinal,W,Z)
bet<-betjj
optimbet<-optim(bet,Quno,esterno1=esterno1,gr=NULL) #added gr
optimparam<-optim(param,Qdue,esterno2=esterno2,q=q,m=m,gr=NULL)
#################################################################
# 7.# Computation of updated estimates and log-likelihood
#################################################################
betjj<-optimbet$par #updated bet estimates
paramjj<-optimparam$par
gamajj<-paramjj[1:(q+1)] #updated gama estimates
alphajj<-paramjj[(q+2):(q+v+2)] #updated alpha estimates
### updated log-likelihood
liknew<-loglikcubecov(m,ordinal,Y,W,Z,betjj,gamajj,alphajj)
#################################################################
# 8.# Checking improvement of updated log-likelihood
#################################################################
# print(c(nniter,betjj,gamajj,loglikjj)); #OPTIONAL PRINTING OF ITERATIONS
testloglik<-abs(liknew-likold)
#print(nniter);##added
#print(round(c(liknew,likold,testloglik),digits=7))#added
if(testloglik<=toler) break else {likold<-liknew}
nniter<-nniter+1
}
#################################################################
# 8.# Final ML estimates and maximized log-likelihood
#################################################################
bet<-betjj; gama<-gamajj; alpha<-alphajj;
loglik<-liknew
###### End of E-M algorithm for CUBE ***********************************************
paramest<-c(bet,gama,alpha)
nparam<- length(paramest) ###p+q+v+3;
AICCUBE<- -2*loglik+2*nparam
BICCUBE<- -2*loglik+log(n)*nparam
############################################################
# Compute asymptotic standard errors of ML CUBE estimates ##
############################################################
varmat<-varcovcubecov(m,ordinal,Y,W,Z,bet,gama,alpha)
#if(det(varmat)<=0) stop("Variance-Covariance matrix NOT positive definite")
# nomi<-c(paste("beta",0:(length(bet)-1),sep="_"),
# paste("gamma",0:(length(gama)-1),sep="_"),
# paste("alpha",0:(length(alpha)-1),sep="_"))
stime<-paramest
if (isTRUE(varmat==matrix(NA,nrow=nparam,ncol=nparam))==TRUE){
ddd<-cormat<-matrix(NA,nrow=nparam,ncol=nparam)
trvarmat<-ICOMP<-NA
errstd<-wald<-pval<-rep(NA,nparam)
} else {
ddd<-diag(sqrt(1/diag(varmat)))
cormat<-(ddd%*%varmat)%*%ddd
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
errstd<-sqrt(diag(varmat)); wald<-stime/errstd;
pval<-2*(1-pnorm(abs(wald)))
}
# rownames(cormat)<-nomi;colnames(cormat)<-nomi;
##################################################
# Print CUBE-covariates results of ML estimation #
durata<-proc.time()-tt0;durata<-durata[1];
##################################################
# if (summary==TRUE){
#cat("=======================================================================","\n")
#cat("Convergence code =",optimparam$convergence,"\n")
results<-list('estimates'=stime, 'loglik'=loglik, 'niter'= nniter,
'varmat'=varmat,'BIC'=BICCUBE,'time'=durata)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubecov.R
|
#' @title Main function for CUBE models with covariates only for feeling
#' @description Estimate and validate a CUBE model for ordinal data, with covariates only for explaining the
#' feeling component.
#' @aliases cubecsi
#' @usage cubecsi(m, ordinal, W, starting, maxiter, toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of selected covariates for explaining the feeling component
#' @param starting Vector of initial parameters estimates to start the optimization algorithm, with length equal to
#' NCOL(W) + 3 to account for an intercept term for the feeling component (first entry)
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @return An object of the class "CUBE". For cubecsi, $niter will return a NULL value since the optimization procedure
#' is not iterative but based on "optim" (method = "L-BFGS-B", option hessian=TRUE). \cr $varmat will return the inverse
#' of the numerically computed Hessian when it is positive definite, otherwise the procedure will return a matrix of NA
#' entries.
#' @import stats
#' @seealso \code{\link{loglikcubecsi}}, \code{\link{inibestcubecsi}}, \code{\link{CUBE}}
#' @keywords internal #models
cubecsi<-function(m,ordinal,W,starting,maxiter,toler){
tt0<-proc.time()
n<-length(ordinal)
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
q<-length(starting)-3
pai<-starting[1]; gama<-starting[2:(q+2)]; phi<-starting[q+3];
#(0)# log-lik
loglikzero<-loglikcubecsi(m,ordinal,W,pai,gama,phi)
#################################################################
param<-c(pai,gama,phi)
##################################
### maximize w.r.t. gama and phi #########
optimparam<-optim(param,effecubecsi,ordinal=ordinal,W=W,m=m,method="L-BFGS-B",lower=c(0.01,rep(-Inf,q+1),0.01), upper=c(0.99,rep(Inf,q+1),0.3),gr=NULL,hessian=TRUE)
#################################################################
# 7.# Computation of updated estimates and log-likelihood
#################################################################
paramest<-optimparam$par
pai<-paramest[1]
gama<-paramest[2:(q+2)] #updated gama estimates
phi<-paramest[q+3] #updated phi estimates
hessian<-optimparam$hessian
### updated log-likelihood
loglik<-loglikcubecsi(m,ordinal,W,pai,gama,phi)
vettestim<-c(pai,gama,phi)
nparam<-length(vettestim)
####################################################################
AICCUBEcsi<- -2*loglik+2*nparam
BICCUBEcsi<- -2*loglik+log(n)*nparam
###########################################################################
# Compute asymptotic standard errors of ML estimates via (numerical)Hessian
###########################################################################
if (det(hessian)<=0){
warning("Variance-Covariance matrix is not positive definite")
varmat<-ddd<-cormat<-matrix(NA,nrow=nparam,ncol=nparam)
errstd<-wald<-pval<-rep(NA,nparam)
ICOMP<-trvarmat<-NA
} else {
varmat<-solve(hessian)
errstd<-sqrt(diag(varmat))
ddd<-diag(sqrt(1/diag(varmat)))
wald<-vettestim/errstd
pval<-2*(1-pnorm(abs(wald)))
cormat<-(ddd%*%varmat)%*%ddd
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
errstd<-errstd
wald<-wald
pval<-pval
}
# nomi<-c("pai ",paste("gamma",0:(length(gama)-1),sep="_"),"phi ")
stime<-vettestim
####################################################################
### Print CUBEcsi results of ML estimation
####################################################################
# rownames(cormat)<-nomi; colnames(cormat)<-nomi;
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'=stime, 'loglik'=loglik, 'varmat'=varmat,
'BIC'= BICCUBEcsi,'time'=durata,'niter'=1)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubecsi.R
|
#' @title Plot an estimated CUBE model
#' @description Plotting facility for the CUBE estimation of ordinal responses.
#' @aliases cubevisual
#' @usage cubevisual(ordinal,csiplot=FALSE,paiplot=FALSE,...)
#' @param ordinal Vector of ordinal responses
#' @param csiplot Logical: should \eqn{\xi} or \eqn{1-\xi} be the \eqn{y} coordinate
#' @param paiplot Logical: should \eqn{\pi} or \eqn{1-\pi} be the \eqn{x} coordinate
#' @param ... Additional arguments to be passed to \code{plot()} and \code{text()}. Optionally, the number \code{m}
#' of ordinal categories may be passed: this is recommended if some category has zero frequency.
#' @details It represents an estimated CUBE model as a point
#' in the parameter space with the overdispersion being labeled.
#' @return For a CUBE model fitted to \code{ordinal}, by default it returns a plot of the estimated
#' \eqn{(1-\pi, 1-\xi)} as a point in the parameter space, labeled with the estimated overdispersion \eqn{\phi}.
#' Depending on \code{csiplot} and \code{paiplot} and on desired output, \eqn{x} and \eqn{y} coordinates may be set
#' to \eqn{\pi} and \eqn{\xi}, respectively.
#' @keywords device
#' @export cubevisual
#' @import graphics
#' @examples
#' data(univer)
#' ordinal<-univer$global
#' cubevisual(ordinal,xlim=c(0,0.5),main="Global Satisfaction",
#' ylim=c(0.5,1),cex=0.8,digits=3,col="red")
cubevisual<-function(ordinal,csiplot=FALSE,paiplot=FALSE,...){
ellipsis.arg<-list(...)
digits<-ellipsis.arg$digits
if (is.null(digits)){
digits<-options()$digits
}
xlim<-ellipsis.arg$xlim
if (is.null(xlim)){
xlim<-c(0,1)
}
ylim<-ellipsis.arg$ylim
if (is.null(ylim)){
ylim<-c(0,1)
}
pos<-ellipsis.arg$pos
if (is.null(pos)){
pos<-3
}
offset<-ellipsis.arg$offset
if (is.null(offset)){
offset<-0.5
}
font<-ellipsis.arg$font
if(is.null(font)){
font<-4
}
pch<-ellipsis.arg$pch
if (is.null(pch)){
pch<-19
}
cex<-ellipsis.arg$cex
if (is.null(cex)){
cex<-0.5
}
col<-ellipsis.arg$col
if (is.null(col)){
col<-"black"
}
main<-ellipsis.arg$main
if(is.null(main)){
main<-"CUBE parameter space"
}
xlab<-ellipsis.arg$xlab
if (is.null(xlab)){
xlab<-expression(paste("Uncertainty ", (1-pi)))
}
ylab<-ellipsis.arg$ylab
if (is.null(ylab)){
ylab<-expression(paste("Feeling ", (1-xi)))
}
m<-ellipsis.arg[['m']]
if (is.null(m)){
ord<-factor(ordinal,ordered=TRUE)
lev<-levels(ord)
m<-length(lev)
}
starting<-inibestcube(m,ordinal)
F0<-Formula(ordinal~0|0|0)
stimacube<-GEM(F0,family="cube",m=m,starting=starting,maxiter = 500, toler = 1e-06)
param<-stimacube$estimates; pai<-param[1];csi<-param[2];phi<-param[3]
valcsi<-1-csi; valpai<-1-pai;
if (csiplot==TRUE){
valcsi<-csi
ylab<-expression(xi)
}
if (paiplot==TRUE){
valpai<-pai
xlab<-expression(pi)
}
plot(valpai,valcsi,main=main,las=1,pch=pch,cex=cex,xlim=xlim,ylim=ylim,
col=col,xlab=xlab,ylab=ylab);
text(valpai,valcsi,labels=bquote(phi == .(round(phi,digits=3))),font=font,pos=pos,offset=offset,cex=cex,col=col)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubevisual.R
|
#' @title Main function for CUB models with covariates for the uncertainty component
#' @description Estimate and validate a CUB model for given ordinal responses, with covariates for explaining
#' the feeling component via a logistic transform.
#' @aliases cubp0
#' @usage cubp0(m, ordinal, Y, maxiter, toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates for explaining the uncertainty component
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @return An object of the class "CUB"
#' @import stats graphics
#' @references
#' Iannario M. and Piccolo D. (2010), A new statistical model for the analysis of customer satisfaction,
#' \emph{Quality Technology and Quantity management}, \bold{7}(2) 149--168 \cr
#' Iannario M. and Piccolo D. (2012). CUB models: Statistical methods and empirical evidence, in:
#' Kenett R. S. and Salini S. (eds.), \emph{Modern Analysis of Customer Surveys: with applications using R},
#' J. Wiley and Sons, Chichester, 231--258
#' @keywords internal
cubp0<-function(m,ordinal,Y,maxiter,toler){
tt0<-proc.time()
n<-length(ordinal)
Y<-as.matrix(Y)
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
p<-NCOL(Y)
aver<-mean(ordinal); varcamp<-mean(ordinal^2)-aver^2;
YY<-cbind(1,Y)
##################################################################
serie<-1:m; freq<-tabulate(ordinal,nbins=m);
inipaicsi<-inibest(m,freq)
pai<-inipaicsi[1]; bet0<-log(pai/(1-pai));
betjj<- c(bet0,rep(0.1,p)) #betjj<-rep(0.1,p+1);
csijj<-inipaicsi[2]
##############################################################
loglikjj<-loglikcubp0(m,ordinal,Y,betjj,csijj)
# ********************************************************************
# ************* E-M algorithm for CUB(p,0) ***************************
# ********************************************************************
nniter<-1
while(nniter<=maxiter){
loglikold<-loglikjj
bb<-probbit(m,csijj)
vettn<-bb[ordinal] # probbit for all ordinal (r_i,i=1,2,...,n)
aai<- -1+ 1/(logis(Y,betjj)) #exp(-(YY%*%betjj));
ttau<-1/(1+aai/(m*vettn)) # tau is a reserved word in R
averpo<-sum(ordinal*ttau)/sum(ttau)
################################## maximize w.r.t. bet ########
bet<-betjj
covar<-YY
tauno<-ttau
#nlmaxbet<-nlm(effe10,betjj,esterno10);
opmaxbet<-optim(bet,effe10,esterno10=cbind(tauno,covar))
################################################################
betjj<-opmaxbet$par
# betjj<-nlmaxbet$estimate; #updated bet estimates
csijj<-(m-averpo)/(m-1) #updated csi estimate
#loglikjj<- -opmaxbet$value
loglikjj<-loglikcubp0(m,ordinal,Y,betjj,csijj)
#print(c(nniter,betjj,csijj,loglikjj)); #OPTIONAL PRINTING OF ITERATIONS
testll<-abs(loglikjj-loglikold)
if(testll<=toler) break else {loglikold<-loglikjj}
nniter<-nniter+1
}
bet<-betjj; csi<-csijj; loglik<-loglikjj;
####################################################################
AICCUBp0<- -2*loglik+2*(p+2)
BICCUBp0<- -2*loglik+log(n)*(p+2)
####################################################################
# Compute asymptotic standard errors of ML estimates
####################################################################
varmat<-varcovcubp0(m,ordinal,Y,bet,csi)
nomi<-c(paste("beta",0:(length(bet)-1),sep="_"),"csi ")
stime<-c(bet,csi)
nparam<-length(stime)
#if(det(varmat)<=0) stop("Variance-covariance matrix NOT positive definite")
if (isTRUE(varmat==matrix(NA,nrow=nparam,ncol=nparam))==TRUE){
ddd<-cormat<-matrix(NA,nrow=nparam,ncol=nparam)
ICOMP<-trvarmat<-NA
errstd<-wald<-pval<-rep(NA,nparam)
} else {
ddd<-diag(sqrt(1/diag(varmat)))
cormat<-(ddd%*%varmat)%*%ddd
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat)) ## added
errstd<-sqrt(diag(varmat)); wald<-stime/errstd;
pval<-2*(1-pnorm(abs(wald)))
}
rownames(cormat)<-nomi;colnames(cormat)<-nomi;
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'=stime,'ordinal'=ordinal,'time'=durata,
'loglik'=loglik,'niter'=nniter,'varmat'=varmat,
'BIC'=BICCUBp0)
#class(results)<-"cub"
return(results)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubp0.R
|
#' @title Main function for CUB models with covariates for both the uncertainty and the feeling components
#' @description Estimate and validate a CUB model for given ordinal responses, with covariates for explaining both the
#' feeling and the uncertainty components by means of logistic transform.
#' @aliases cubpq
#' @usage cubpq(m, ordinal, Y, W, maxiter, toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates for explaining the uncertainty component
#' @param W Matrix of selected covariates for explaining the feeling component
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @return An object of the class "CUB"
#' @import stats
#' @seealso \code{\link{varcovcubpq}}, \code{\link{loglikcubpq}}, \code{\link{inibestgama}}, \code{\link{CUB}}
#' @references
#' Piccolo D. and D'Elia A. (2008), A new approach for modelling consumers' preferences, \emph{Food Quality and Preference},
#' \bold{18}, 247--259 \cr
#' Iannario M. and Piccolo D. (2010), A new statistical model for the analysis of customer satisfaction,
#' \emph{Quality Technology and Quantitative Management}, \bold{17}(2) 149--168
#' @keywords internal
########################################
cubpq<-function(m,ordinal,Y,W,maxiter,toler){
tt0<-proc.time()
n<-length(ordinal)
Y<-as.matrix(Y)
W<-as.matrix(W)
p<-NCOL(Y)
q<-NCOL(W)
aver<-mean(ordinal)
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(W)==1){
W<-as.numeric(W)
}
YY<-cbind(1,Y); WW<-cbind(1,W);
#################################################################################
freq<-tabulate(ordinal,nbins=m)
inipaicsi<-inibest(m,freq); pai<-inipaicsi[1]; bet0<-log(pai/(1-pai)); betjj<-c(bet0,rep(0.1,p));
gamajj<-inibestgama(m,factor(ordinal,ordered=TRUE),W)
#################################################################################
loglikjj<-loglikcubpq(m,ordinal,Y,W,betjj,gamajj)
# ********************************************************************
# ************* E-M algorithm for CUB(p,q) ***************************
# ********************************************************************
nniter<-1
while(nniter<=maxiter){
loglikold<-loglikjj
vettn<-as.numeric(bitgama(m,factor(ordinal,ordered=TRUE),W,gamajj) )
aai<- -1+1/(logis(Y,betjj))
ttau<-1/(1+aai/(m*vettn))
#################### maximize w.r.t. bet and gama ############
esterno10<-cbind(ttau,YY)
esterno01<-cbind(ttau,ordinal,WW)
bet<-betjj; gama<-gamajj;
betoptim<-optim(bet,effe10,esterno10=esterno10)
gamaoptim<-optim(gama,effe01,esterno01=esterno01,m=m)
################################################################
betjj<-betoptim$par
gamajj<-gamaoptim$par
loglikjj<-loglikcubpq(m,ordinal,Y,W,betjj,gamajj)
# print(c(nniter,betjj,gamajj,loglikjj)); #OPTIONAL PRINTING OF ITERATIONS
testll<-abs(loglikjj-loglikold)
if(testll<=toler) break else {loglikold<-loglikjj}
nniter<-nniter+1
}
bet<-betjj; gama<-gamajj; loglik<-loglikjj;
####################################################################
AICCUBpq<- -2*loglik+2*(p+q+2)
BICCUBpq<- -2*loglik+log(n)*(p+q+2)
####################################################################
# Compute asymptotic standard errors of ML estimates
####################################################################
varmat<-varcovcubpq(m,ordinal,Y,W,bet,gama)
#if(det(varmat)<=0) stop("Variance-covariance matrix NOT positive definite")
nomi<-c(paste("beta",0:(length(bet)-1),sep="_"),paste("gamma",0:(length(gama)-1),sep="_"))
stime<-c(bet,gama)
nparam<-length(stime)
if (isTRUE(varmat==matrix(NA,nrow=nparam,ncol=nparam))==TRUE){
ddd<-cormat<-matrix(NA,nrow=nparam,ncol=nparam)
ICOMP<-trvarmat<-NA
errstd<-wald<-pval<-rep(NA,nparam)
} else {
ddd<-diag(sqrt(1/diag(varmat)))
cormat<-(ddd%*%varmat)%*%ddd
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
errstd<-sqrt(diag(varmat)); wald<-stime/errstd;
pval<-2*(1-pnorm(abs(wald)))
}
rownames(cormat)<-nomi;colnames(cormat)<-nomi;
durata<-proc.time()-tt0;durata<-durata[1];
####################################################################
results<-list('estimates'=stime,'ordinal'=ordinal,'time'=durata,
'loglik'=loglik,'niter'=nniter,'varmat'=varmat,
'BIC'=BICCUBpq)
#class(results)<-"cub"
return(results)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubpq.R
|
#' @title Main function for CUB models with a shelter effect
#' @description Estimate and validate a CUB model with a shelter effect.
#' @aliases cubshe
#' @usage cubshe(m, ordinal, shelter, maxiter, toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param shelter Category corresponding to the shelter choice
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @return An object of the class "CUB"
#' @import stats
#' @references
#' Iannario M. (2012). Modelling \emph{shelter} choices in a class of mixture models for ordinal responses,
#' \emph{Statistical Methods and Applications}, \bold{21}, 1--22
#' @keywords internal #models
cubshe<-function(m,ordinal,shelter,maxiter,toler){
tt0<-proc.time()
#######
###########
serie<-1:m; freq<-tabulate(ordinal,nbins=m); n<-sum(freq);
##########
###########
aver<-mean(ordinal); varcamp<-mean(ordinal^2)-aver^2;
dd<-ifelse(serie==shelter,1,0)
#####################################################################
vett<-inibest(m,freq)
pai1<-vett[1]; csi<-vett[2]
fc<-freq[shelter]/n
deltaini<-max(0.01,(m*fc-1)/(m-1)) #deltaini=runif(1,0,0.3)
pai2<-max(0.01,1-deltaini-pai1)
################################################################
loglik<-loglikcubshe(m,freq,pai1,pai2,csi,shelter)
# ********************************************************************
# ************* E-M algorithm for CUBSHE *****************************
# ********************************************************************
nniter<-1
while(nniter<=maxiter){
#############
likold<-loglik
bb<-probbit(m,csi)
tau1<-pai1*bb
tau2<-pai2*(1/m)
denom<-tau1+tau2+(1-pai1-pai2)*dd
tau1<-tau1/denom
tau2<-tau2/denom
tau3<-1-tau1-tau2
numaver<-sum(serie*freq*tau1)
denaver<-sum(freq*tau1)
averpo<-numaver/denaver
pai1<-sum(freq*tau1)/n #updated pai1 estimate
pai2<-sum(freq*tau2)/n #updated pai2 estimate
csi<-(m-averpo)/(m-1) #updated csi estimate
if(csi<0.001){
csi<-0.001;nniter<-maxiter-1;
}
loglik<-loglikcubshe(m,freq,pai1,pai2,csi,shelter)
liknew<-loglik
testll<-abs(liknew-likold)
#print(cbind(nniter,testll,pai1,pai2,csi,loglik));
if(testll<=toler) break else {loglik<-liknew}
nniter<-nniter+1
}
######
if(csi>0.999) csi<-0.99 ###????????### to avoid division by 0 !!!
if(csi<0.001) csi<-0.01 ###????### to avoid division by 0 !!!
if(pai1<0.001) pai1<-0.01 ###????? ### to ensure identifiability !!!
####################################################################
# Compute asymptotic standard errors of ML estimates
####################################################################
varmat<-varcovcubshe(m,pai1,pai2,csi,shelter,n)
nomi<-rbind("pai1","pai2","csi")
stime<-c(pai1,pai2,csi)
nparam<-length(stime)
delta<-1-pai1-pai2
paistar<-pai1/(pai1+pai2)
if (isTRUE(varmat==matrix(NA,nrow=nparam,ncol=nparam))==TRUE){
ddd<-cormat<-matrix(NA,nrow=nparam,ncol=nparam)
ICOMP<-trvarmat<-NA
esdelta<-pvaldelta<-espaistar<-pvalpaistar<-NA
errstd<-wald<-pval<-rep(NA,nparam)
} else {
ddd<-diag(sqrt(1/diag(varmat)))
esdelta<-sqrt(varmat[1,1]+varmat[2,2]+2*varmat[1,2])
pvaldelta<-round(2*(1-pnorm(abs(delta/esdelta))),20)
espaistar<-sqrt((pai1^2*varmat[2,2]+pai2^2*varmat[1,1]-2*pai1*pai2*varmat[1,2]))/(pai1+pai2)^2
pvalpaistar<-round(2*(1-pnorm(abs(paistar/espaistar))),20)
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
errstd<-sqrt(diag(varmat))
wald<-stime/errstd
pval<-round(2*(1-pnorm(abs(wald))),20)
}
theorpr<-probcubshe1(m,pai1,pai2,csi,shelter)
dissshe<-dissim(theorpr,freq/n)
llunif<- -n*log(m); csisb<-(m-aver)/(m-1);
llsb<-loglikcub00(m,freq,1,csisb)
llunif<- -n*log(m)
nonzero<-which(freq!=0)
logsat<- -n*log(n)+sum((freq[nonzero])*log(freq[nonzero]))
pearson<-((freq-n*theorpr))/sqrt(n*theorpr)
X2<-sum(pearson^2)
relares<-(freq/n-theorpr)/theorpr
stampa<-cbind(1:m,freq/n,theorpr,pearson,relares)
LL2<-1/(1+mean((freq/(n*theorpr)-1)^2))
II2<-(loglik-llunif)/(logsat-llunif)
FF2<-1-dissshe
AICCUBshe<- -2*loglik+2*(3)
BICCUBshe<- -2*loglik+log(n)*(3)
durata<-proc.time()-tt0;durata<-durata[1];
#
results<-list('estimates'=stime,'ordinal'=ordinal,'time'=durata,
'loglik'=loglik,'niter'=nniter,'varmat'=varmat,
'BIC'=BICCUBshe)
#class(results)<-"cub"
return(results)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubshe.R
|
#' @title Plot an estimated CUB model with shelter
#' @description Plotting facility for the CUB estimation of ordinal responses when a shelter effect is included
#' @aliases cubshevisual
#' @usage cubshevisual(ordinal,shelter,csiplot=FALSE,paiplot=FALSE,...)
#' @param ordinal Vector of ordinal responses
#' @param shelter Category corresponding to the shelter choice
#' @param csiplot Logical: should \eqn{\xi} or \eqn{1-\xi} be the \eqn{y} coordinate
#' @param paiplot Logical: should \eqn{\pi} or \eqn{1-\pi} be the \eqn{x} coordinate
#' @param ... Additional arguments to be passed to \code{plot()} and \code{text()}. Optionally, the number \code{m}
#' of ordinal categories may be passed: this is recommended if some category has zero frequency.
#' @details It represents an estimated CUB model with shelter effect as a point
#' in the parameter space with shelter estimate indicated as label.
#' @return For a CUB model with shelter fitted to \code{ordinal}, by default it returns a plot of the estimated
#' \eqn{(1-\pi, 1-\xi)} as a point in the parameter space, labeled with the estimated shelter parameter \eqn{\delta}.
#' Depending on \code{csiplot} and \code{paiplot} and on desired output, \eqn{x} and \eqn{y} coordinates may be set
#' to \eqn{\pi} and \eqn{\xi}, respectively.
#' @keywords device
#' @export cubshevisual
#' @seealso \code{\link{cubvisual}}, \code{\link{multicub}}
#' @import graphics
#' @examples
#' data(univer)
#' ordinal<-univer$global
#' cubshevisual(ordinal,shelter=7,digits=3,col="blue",main="Global Satisfaction")
cubshevisual<-function(ordinal,shelter,csiplot=FALSE,paiplot=FALSE,...){
ellipsis.arg<-list(...)
digits<-ellipsis.arg$digits
if (is.null(digits)){
digits<-options()$digits
}
pos<-ellipsis.arg$pos
if (is.null(pos)){
pos<-3
}
offset<-ellipsis.arg$offset
if (is.null(offset)){
offset<-0.5
}
font<-ellipsis.arg$font
if(is.null(font)){
font<-4
}
main<-ellipsis.arg$main
if (is.null(main)){
main<-"CUB-she parameter space"
}
xlim<-ellipsis.arg$xlim
if (is.null(xlim)){
xlim=c(0,1)
}
ylim<-ellipsis.arg$ylim
if (is.null(ylim)){
ylim<-c(0,1)
}
pch<-ellipsis.arg$pch
if (is.null(pch)){
pch<-19
}
cex<-ellipsis.arg$cex
if (is.null(cex)){
cex<-0.5
}
col<-ellipsis.arg$col
if (is.null(col)){
col<-"black"
}
xlab<-ellipsis.arg$xlab
if (is.null(xlab)){
xlab<-expression(paste("Uncertainty ", (1-pi)))
}
ylab<-ellipsis.arg$ylab
if (is.null(ylab)){
ylab<-expression(paste("Feeling ", (1-xi)))
}
m<-ellipsis.arg[['m']]
if (is.null(m)){
ord<-factor(ordinal,ordered=TRUE)
lev<-levels(ord)
m<-length(lev)
}
F0<-Formula(ordinal~0|0|0)
#data<-as.data.frame(ordinal)
mod<-GEM(F0,shelter=shelter,family="cub",m=m)
stime<-mod$estimates
pai1<-stime[1];pai2<-stime[2];csi<-stime[3]
deltaval<-round(1-pai1-pai2,digits=digits)
paistar<-pai1/(pai1+pai2)
valcsi<-1-csi; valpai<-1-paistar;
if (csiplot==TRUE){
valcsi<-csi
ylab<-expression(xi)
}
if (paiplot==TRUE){
valpai<-paistar
xlab<-expression(pi)
}
plot(valpai,valcsi,pch=pch,col=col,main=main,xlim=xlim,ylim=ylim,xlab=xlab,
ylab=ylab)
text(valpai,valcsi,labels=bquote(delta == .(deltaval)),pos=pos,offset=offset,font=font,cex=cex,col=col)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubshevisual.R
|
#' @title Plot an estimated CUB model
#' @description Plotting facility for the CUB estimation of ordinal responses.
#' @aliases cubvisual
#' @usage cubvisual(ordinal,csiplot=FALSE,paiplot=FALSE,...)
#' @param ordinal Vector of ordinal responses
#' @param csiplot Logical: should \eqn{\xi} or \eqn{1-\xi} be the \eqn{y} coordinate
#' @param paiplot Logical: should \eqn{\pi} or \eqn{1-\pi} be the \eqn{x} coordinate
#' @param ... Additional arguments to be passed to \code{plot()} and \code{text()}. Optionally, the number
#' \code{m} of ordinal categories may be passed: this is recommended if some category has zero frequency.
#' @details It represents an estimated CUB model as a point
#' in the parameter space with some useful options.
#' @return For a CUB model fit to \code{ordinal}, by default it returns a plot of the estimated
#' \eqn{(1-\pi, 1-\xi)} as a point in the parameter space. Depending on \code{csiplot} and \code{paiplot}
#' and on desired output, \eqn{x} and \eqn{y} coordinates may be set to \eqn{\pi} and \eqn{\xi}, respectively.
#' @keywords device
#' @export cubvisual
#' @import graphics
#' @examples
#' data(univer)
#' ordinal<-univer$global
#' cubvisual(ordinal,xlim=c(0,0.5),ylim=c(0.5,1),cex=0.8,main="Global Satisfaction")
cubvisual<-function(ordinal,csiplot=FALSE,paiplot=FALSE,...){
ellipsis.arg<-list(...)
xlim<-ellipsis.arg$xlim
if (is.null(xlim)){
xlim<-c(0,1)
}
ylim<-ellipsis.arg$ylim
if (is.null(ylim)){
ylim<-c(0,1)
}
pos<-ellipsis.arg$pos
if (is.null(pos)){
pos<-3
}
offset<-ellipsis.arg$offset
if (is.null(offset)){
offset<-0.5
}
font<-ellipsis.arg$font
if(is.null(font)){
font<-4
}
pch<-ellipsis.arg$pch
if (is.null(pch)){
pch<-19
}
cex<-ellipsis.arg$cex
if (is.null(cex)){
cex<-0.5
}
col<-ellipsis.arg$col
if (is.null(col)){
col<-"black"
}
xlab<-ellipsis.arg$xlab
if (is.null(xlab)){
xlab<-expression(paste("Uncertainty ", (1-pi)))
}
ylab<-ellipsis.arg$ylab
if (is.null(ylab)){
ylab<-expression(paste("Feeling ", (1-xi)))
}
main<-ellipsis.arg$main
if (is.null(main)){
main<-"CUB parameter space"
}
m<-ellipsis.arg[['m']]
if (is.null(m)){
ord<-factor(ordinal,ordered=TRUE)
lev<-levels(ord)
m<-length(lev)
}
F0<-Formula(ordinal~0|0|0)
#data<-as.data.frame(ordinal)
stimacub<-GEM(F0,family="cub",m=m,maxiter = 500, toler = 1e-06)
param<-stimacub$estimates; pai<-param[1];csi<-param[2];
valcsi<-1-csi; valpai<-1-pai;
if (csiplot==TRUE){
valcsi<-csi
ylab<-expression(xi)
}
if (paiplot==TRUE){
valpai<-pai
xlab<-expression(pi)
}
plot(valpai,valcsi,main=main,las=1,pch=pch,cex=cex,xlim=xlim,ylim=ylim,
col=col,xlab=xlab, ylab=ylab)
text(valpai,valcsi,labels="estim",font=font,pos=pos,offset=offset,cex=cex,col=col)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cubvisual.R
|
#' @title CUSH model without covariates
#' @description Estimate and validate a CUSH model for given ordinal responses, without covariates.
#' @usage cush00(m, ordinal, shelter)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param shelter Category corresponding to the shelter choice
#' @keywords internal
#' @aliases cush00
#' @return An object of the class "GEM", "CUSH"
#' @import stats graphics
cush00<-function(m,ordinal,shelter){
tt0<-proc.time()
freq<-tabulate(ordinal,nbins=m); n<-length(ordinal); aver<-mean(ordinal);
fc<-freq[shelter]/n
deltaest<-max(0.01,(m*fc-1)/(m-1)) ### sufficient unbiased estimator
esdelta<-sqrt((1-deltaest)*(1+(m-1)*deltaest)/(n*(m-1)))
varmat<-esdelta^2
wald<-deltaest/esdelta
loglik<-loglikcush00(m,ordinal,deltaest,shelter)
AICCUSH<- -2*loglik+2
BICCUSH<- -2*loglik+log(n)
llunif<- -n*log(m); csisb<-(m-aver)/(m-1);
llsb<-loglikcub00(m,freq,1,csisb)
nonzero<-which(freq!=0)
logsat<- -n*log(n)+sum((freq[nonzero])*log(freq[nonzero]))
devian<-2*(logsat-loglik)
LRT<-2*(loglik-llunif)
theorpr<-deltaest*ifelse(seq(1,m)==shelter,1,0)+(1-deltaest)/m
pearson<-((freq-n*theorpr))/sqrt(n*theorpr)
X2<-sum(pearson^2)
relares<-(freq/n-theorpr)/theorpr
diss00<-dissim(theorpr,freq/n)
FF2<-1-diss00
LL2<-1/(1+mean((freq/(n*theorpr)-1)^2))
II2<-(loglik-llunif)/(logsat-llunif)
stampa<-cbind(1:m,freq/n,theorpr,pearson,relares)
durata<-proc.time()-tt0; durata<-durata[1];
###########
####################################
results<-list('estimates'=deltaest, 'loglik'=loglik,
'varmat'=varmat,'BIC'= BICCUSH,'time'=durata)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cush00.R
|
#' @title CUSH model with covariates
#' @description Estimate and validate a CUSH model for ordinal responses, with covariates
#' to explain the shelter effect.
#' @aliases cushcov
#' @usage cushcov(m, ordinal, X, shelter)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param X Matrix of selected covariates for explaining the shelter effect
#' @param shelter Category corresponding to the shelter choice
#' @keywords internal
#' @return An object of the class "GEM", "CUSH"
#' @import stats graphics
###########################################################################################
### CUSHCOV (shelter) with covariates
###########################################################################################
cushcov<-function(m,ordinal,X,shelter){
tt0<-proc.time()
freq<-tabulate(ordinal,nbins=m); n<-length(ordinal);
fc<-freq[shelter]/n
delta<-max(0.01,(m*fc-1)/(m-1)) ### sufficient unbiased estimator for a CUSH model
X<-as.matrix(X)
if (ncol(X)==1){
X<-as.numeric(X)
}
ncovar<-NCOL(X)
omzero<-log(delta/(1-delta)) ### initial estimate of omega_0
omegainit<-c(omzero,rep(0.1,ncovar)) ### initial estimate of omega vector
### maximize w.r.t. omega
XX<-cbind(1,X)
esternocush<-cbind(ordinal,XX)
paravec<-omegainit
shelter<-shelter
optimomega<-optim(paravec,effecush,esternocush,shelter=shelter,m=m,gr=NULL,hessian=TRUE)
#################################################################
# Computation of estimates and log-likelihood
#################################################################
omegaest<-optimomega$par #omega estimates
loglik<-loglikcushcov(m,ordinal,X,omegaest,shelter) #loglik at the maximum
HHH<-optimomega$hessian
nparam<-length(omegaest)
if (det(HHH)<=0){
warning("Variance-Covariance matrix is not positive definite")
varmat<-ddd<-cormat<-matrix(NA,nrow=nparam,ncol=nparam)
trvarmat<-ICOMP<-NA
errst<-wald<-pval<-rep(NA,nparam)
} else {
varmat<-solve(HHH)
errst<-sqrt(diag(varmat)) ### vector
ddd<-diag(sqrt(1/diag(varmat))) ### matrix
wald<-omegaest/errst
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat)) ## added
}
AICCUSH<- -2*loglik+2*nparam
BICCUSH<- -2*loglik+nparam*log(n)
nomi<-c(paste("omega",0:(nparam-1),sep="_"))
stime<-omegaest; errstd<-errst; wald<-wald;
pval<-2*(1-pnorm(abs(wald)))
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'=stime, 'loglik'=loglik, 'varmat'=varmat,'BIC'=BICCUSH,
'time'=durata)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/cushcov.R
|
#' @title Mean difference of a discrete random variable
#' @description Compute the Gini mean difference of a discrete distribution
#' @usage deltaprob(prob)
#' @aliases deltaprob
#' @param prob Vector of the probability distribution
#' @keywords univar
#' @return Numeric value of the Gini mean difference of the input probability distribution,
#' computed according to the de Finetti-Paciello formulation.
#' @export deltaprob
#' @examples
#' prob<-c(0.04,0.04,0.05,0.10,0.21,0.32,0.24)
#' deltaprob(prob)
deltaprob <-
function(prob){
frip<-cumsum(prob)
m<-length(prob)
frip1<-frip[1:(m-1)]
2*sum(frip1*(1-frip1))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/deltaprob.R
|
#' @title Normalized dissimilarity measure
#' @description Compute the normalized dissimilarity measure between observed
#' relative frequencies and estimated (theoretical) probabilities of a discrete distribution.
#' @usage dissim(proba,probb)
#' @aliases dissim
#' @param proba Vector of observed relative frequencies
#' @param probb Vector of estimated (theoretical) probabilities
#' @return Numeric value of the dissimilarity index, assessing the distance to a perfect fit.
#' @keywords univar
#' @export dissim
#' @examples
#' proba<-c(0.01,0.03,0.08,0.07,0.27,0.37,0.17)
#' probb<-c(0.04,0.04,0.05,0.10,0.21,0.32,0.24)
#' dissim(proba,probb)
dissim <-
function(proba,probb){
if (length(proba)==length(probb)){
return(0.5*sum(abs(proba-probb)))
} else {
cat("Error: input vectors should have the same length","\n")
}
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/dissim.R
|
#' @title Auxiliary function for the log-likelihood estimation of CUB models
#' @description Compute the opposite of the scalar function that is maximized when running
#' the E-M algorithm for CUB models with covariates for the feeling parameter.
#' @aliases effe01
#' @usage effe01(gama, esterno01, m)
#' @param gama Vector of the starting values of the parameters to be estimated
#' @param esterno01 A matrix binding together the vector of the posterior probabilities
#' that each observation has been generated by the first component distribution of the mixture,
#' the ordinal data and the matrix of the selected covariates accounting for an intercept term
#' @keywords internal
#' @details It is called as an argument for optim within CUB function for models with covariates for
#' feeling or for both feeling and uncertainty
effe01 <-
function(gama,esterno01,m){
ttau<-esterno01[,1]
ordd<-esterno01[,2]
covar<-esterno01[,3:ncol(esterno01)]
return(sum(ttau*((ordd-1)*(covar%*%gama)+(m-1)*log(1+exp(-covar%*%gama)))))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/effe01.R
|
#' @title Auxiliary function for the log-likelihood estimation of CUB models
#' @description Compute the opposite of the scalar function that is maximized when running
#' the E-M algorithm for CUB models with covariates for the uncertainty parameter.
#' @aliases effe10
#' @usage effe10(bet, esterno10)
#' @param bet Vector of the starting values for the parameters to be estimated
#' @param esterno10 A matrix binding together the matrix of the selected covariates
#' (accounting for an intercept term) and a vector (whose length equals the number of observations)
#' of the posterior probabilities that each observation has been generated by the first component
#' distribution of the mixture
#' @keywords internal
#' @details It is called as an argument for optim within CUB function for models with covariates for
#' uncertainty or for both feeling and uncertainty
effe10 <-
function(bet,esterno10){
tauno<-esterno10[,1]
covar<-esterno10[,2:ncol(esterno10)]
return(sum(log(1+exp(-covar%*%bet))+(1-tauno)*(covar%*%bet)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/effe10.R
|
#' @title Auxiliary function for the log-likelihood estimation of CUBE models without covariates
#' @description Define the opposite of the scalar function that is maximized when running the E-M
#' algorithm for CUBE models without covariates.
#' @aliases effecube
#' @usage effecube(paravec, dati, m)
#' @param paravec Vector of initial estimates for the feeling and the overdispersion parameters
#' @param dati Matrix binding together a column vector of length \eqn{m} containing the posterior
#' probabilities that each observed category has been generated by the first component distribution
#' of the mixture, and the column vector of the absolute frequencies of the observations
#' @keywords internal
#' @details It is called as an argument for optim within CUBE function (where no covariate is specified)
#' and "cubeforsim" as the function to minimize.
#' @references Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 \cr
effecube <- function(paravec,dati,m){
tauno<-dati[,1]
freq<-dati[,2]
return(-sum(freq*tauno*log(betar(m,paravec[1],paravec[2]))))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/effecube.R
|
#' @title Auxiliary function for the log-likelihood estimation of CUBE models with covariates
#' only for the feeling component
#' @description Compute the opposite of the scalar function that is maximized when running the
#' E-M algorithm for CUBE models with covariates only for the feeling component.
#' @aliases effecubecsi
#' @usage effecubecsi(param, ordinal, W, m)
#' @param param Vector of length equal to NCOL(W) + 3 whose entries are the initial parameters estimates
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of the selected covariates for explaining the feeling component
#' @param m Number of ordinal categories
#' @keywords internal
effecubecsi <-
function(param,ordinal,W,m){
q<-length(param)-3
pai<-param[1]
gama<-param[2:(q+2)]
phi<-param[q+3]
-loglikcubecsi(m,ordinal,W,pai,gama,phi)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/effecubecsi.R
|
#' @title Auxiliary function for the log-likelihood estimation of CUSH models with covariates
#' @description Compute the opposite of the loglikelihood function for CUSH models
#' with covariates to explain the shelter effect.
#' @aliases effecush
#' @usage effecush(paravec, esternocush, shelter, m)
#' @param paravec Vector of the initial parameters estimates
#' @param esternocush Matrix binding together the vector of ordinal data and the matrix XX of explanatory
#' variables whose first column is a column of ones needed to consider an intercept term
#' @param shelter Category corresponding to the shelter choice
#' @param m Number of ordinal categories
#' @keywords internal
#' @details It is called as an argument for "optim" within CUSH function (when no covariate is included)
#' as the function to minimize.
effecush <-function(paravec,esternocush,shelter,m){
ordinal<-esternocush[,1]
ncovar<-ncol(esternocush)
X<-esternocush[,3:ncovar]
return(-loglikcushcov(m,ordinal,X,paravec,shelter))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/effecush.R
|
#' @title Auxiliary function for the log-likelihood estimation of IHG models without covariates
#' @description Compute the opposite of the log-likelihood function for an IHG model without covariates.
#' @aliases effeihg
#' @usage effeihg(theta, m, freq)
#' @param theta Initial estimate for the parameter of the IHG distribution
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequency distribution of the ordinal responses
#' @keywords internal
#' @details It is called as an argument for "optim" within IHG function (when no covariate is specified)
#' as the function to minimize.
effeihg <-
function(theta,m,freq){-loglikihg(m,freq,theta)}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/effeihg.R
|
#' @title Auxiliary function for the log-likelihood estimation of IHG models with covariates
#' @description Compute the opposite of the log-likelihood function for an IHG model with covariates
#' for the preference parameter.
#' @aliases effeihgcov
#' @usage effeihgcov(nu, ordinal, U, m)
#' @param nu Vector of the starting values for the parameters to be estimated, with length equal to
#' NCOL(U)+1 to account for an intercept term (first entry of \eqn{nu})
#' @param ordinal Vector of ordinal responses
#' @param U Matrix of the explanatory variables for the preference parameter \eqn{\theta}
#' @param m Number of ordinal categories
#' @keywords internal
#' @details It is called as an argument for "optim" within IHG function (with covariates)
#' as the function to minimize.
effeihgcov <-
function(nu,ordinal,U,m){
-loglikihgcov(m,ordinal,U,nu)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/effeihgcov.R
|
#' @title Log-likelihood function of a CUB model without covariates
#' @description Compute the log-likelihood function of a CUB model without covariates fitting
#' ordinal responses, possibly with subjects' specific parameters.
#' @aliases ellecub
#' @usage ellecub(m,ordinal,assepai,assecsi)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param assepai Vector of uncertainty parameters for given observations
#' (with the same length as \code{ordinal})
#' @param assecsi Vector of feeling parameters for given observations
#' (with the same length as \code{ordinal})
#' @seealso \code{\link{loglikCUB}}
#' @keywords htest
#' @export ellecub
#' @examples
#' m<-7
#' n0<-230
#' n1<-270
#' bet<-c(-1.5,1.2)
#' gama<-c(0.5,-1.2)
#' pai0<-logis(0,bet); csi0<-logis(0,gama)
#' pai1<-logis(1,bet); csi1<-logis(1,gama)
#' ordinal0<-simcub(n0,m,pai0,csi0)
#' ordinal1<-simcub(n1,m,pai1,csi1)
#' ordinal<-c(ordinal0,ordinal1)
#' assepai<-c(rep(pai0,n0),rep(pai1,n1))
#' assecsi<-c(rep(csi0,n0),rep(csi1,n1))
#' lli<-ellecub(m,ordinal,assepai,assecsi)
ellecub <-
function(m,ordinal,assepai,assecsi){
prob<-assepai*(dbinom(0:(m-1),m-1,1-assecsi)-1/m)+1/m
pconi<-prob[ordinal]
return(sum(log(pconi)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/ellecub.R
|
#' @title Log-likelihood function for gecub distribution
#' @description Log-likelihood function for gecub distribution
#' @aliases ellegecub
#' @usage ellegecub(ordinal,Y,W,X,bet,gama,omega,shelter)
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates for explaining the uncertainty component, not including intercept
#' @param W Matrix of selected covariates for explaining the feeling component, not including intercept
#' @param X Matrix of selected covariates for explaining the shelter effect, not including intercept
#' @param bet Matrix of selected covariates for explaining the uncertainty component, not including intercept
#' @param gama Matrix of selected covariates for explaining the feeling component, not including intercept
#' @param omega Matrix of selected covariates for explaining the shelter effect, not including intercept
#' @param shelter Category corresponding to the shelter choice
#' @keywords internal
ellegecub<-function(ordinal,Y,W,X,bet,gama,omega,shelter){
probn<-probgecub(ordinal,Y,W,X,bet,gama,omega,shelter);
return(sum(log(probn)));
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/ellegecub.R
|
#' @title Expectation of CUB distributions
#' @description Compute the expectation of a CUB model without covariates.
#' @aliases expcub00
#' @usage expcub00(m,pai,csi)
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @export expcub00
#' @seealso \code{\link{varcub00}}, \code{\link{expcube}}, \code{\link{varcube}}
#' @keywords distribution
#' @references Piccolo D. (2003). On the moments of a mixture of uniform and shifted binomial random variables.
#' \emph{Quaderni di Statistica}, \bold{5}, 85--104
#' @examples
#' m<-10
#' pai<-0.3
#' csi<-0.7
#' meancub<-expcub00(m,pai,csi)
expcub00 <-
function(m,pai,csi){(m-1)*pai*(0.5-csi)+(m+1)/2}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/expcub00.R
|
#' @title Expectation of CUBE models
#' @description Compute the expectation of a CUBE model without covariates.
#' @aliases expcube
#' @usage expcube(m,pai,csi,phi)
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @param phi Overdispersion parameter
#' @export expcube
#' @seealso \code{\link{varcube}}, \code{\link{varcub00}}, \code{\link{expcub00}}
#' @keywords distribution
#' @references Iannario M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786 \cr
#' Iannario, M. (2015). Detecting latent components in ordinal data with overdispersion by means
#' of a mixture distribution, \emph{Quality & Quantity}, \bold{49}, 977--987
#' @examples
#' m<-10
#' pai<-0.1
#' csi<-0.7
#' phi<-0.2
#' meancube<-expcube(m,pai,csi,phi)
expcube <-
function(m,pai,csi,phi){expcub00(m,pai,csi)}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/expcube.R
|
#' @title S3 method "fitted" for class "GEM"
#' @description S3 method fitted for objects of class \code{\link{GEM}}.
#' @aliases fitted.GEM
#' @param object An object of class \code{\link{GEM}}
#' @param ... Other arguments
#' @method fitted GEM
#' @export
#' @details Returns the fitted probability distribution for GEM models with no covariates. If only one dichotomous
#' covariate is included in the model to explain some components, it returns the fitted probability distribution for each profile.
#' @import methods
#' @seealso \code{GEM}
#' @rdname fitted.GEM
#' @keywords package
#' @examples
#' fitcub<-GEM(Formula(global~0|freqserv|0),family="cub",data=univer)
#' fitted(fitcub,digits=4)
#fitted <- function(object,...) UseMethod("fitted", object)
fitted.GEM<-function(object, ...){
arguments<-list(...)
digits<-arguments$digits
if (is.null(digits)){
digits<-options()$digits
}
theorpr<-profiles(object)
return(round(theorpr,digits=digits))
}
profiles <- function(object) UseMethod("profiles", object)
profiles.CUB<-function(object){
ellipsis<-object$ellipsis
m<-ellipsis[['m']]
values<-c()
for (j in 1:m){
values[j]<-paste("R =",j)
}
stime<-object$estimates
modello<-object$formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
covpai<-model.matrix(modello,data=mf,rhs=1)
covcsi<-model.matrix(modello,data=mf,rhs=2)
covshe<-model.matrix(modello,data=mf,rhs=3)
if (ncol(covpai)==0){
Y<-NULL
} else {
Y<-covpai[,-1]
}
if (ncol(covcsi)==0){
W<-NULL
} else {
W<-covcsi[,-1]
}
if (ncol(covshe)==0){
X<-NULL
} else {
X<-covshe[,-1]
}
if (!is.null(ellipsis$shelter)){
shelter<-ellipsis$shelter
#nomi<-rbind("pai1","pai2","csi")
pai1<-stime[1];pai2<-stime[2];csi<-stime[3]
delta<-1-pai1-pai2
paistar<-pai1/(pai1+pai2)
nprof<-1
theorpr<-matrix(NA,nrow=m,ncol=nprof)
theorpr[,1]<-probcubshe1(m,pai1,pai2,csi,shelter)
profili<-""
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
if ( is.null(W) & is.null(Y)){
# nomi<-rbind("pai","csi");
pai<-stime[1];csi<-stime[2];
nprof<-1
theorpr<-matrix(NA,nrow=m,ncol=nprof)
theorpr[,1]<-probcub00(m,pai,csi)
profili<-""
dimnames(theorpr)<-list(values,profili)
return(theorpr)
}
if (is.null(W) & !is.null(Y)) {
bet<-stime[1:(length(stime)-1)]; csi<-stime[length(stime)]
#nomi<-c(paste("beta",0:(length(bet)-1),sep="_"),"csi ")
#Y<-as.matrix(ellipsis$Y)
if (NCOL(Y)==1 && length(unique(Y))==2) {
Y<-as.matrix(Y)
ny<-NCOL(Y)
yval<-list()
for (j in 1:ny){
yval[[j]]<-sort(unique(Y[,j]))
}
profiles<-expand.grid(yval)
nprof<-NROW(profiles)
theorpr<-matrix(NA,nrow=m,ncol=nprof)
#paivett<-unique(logis(Y,bet))
paivett<-c()
profili<-c()
for (j in 1:nprof){
profili[j]<-"("
paivett[j]<-1/(1+ exp(-bet[1]-sum(as.numeric(profiles[j,])*bet[2:length(bet)])))
theorpr[,j]<-probcub00(m,paivett[j],csi)
for (k in 1:NCOL(profiles)){
profili[j]<-paste(profili[j],"Y",k,"=",profiles[j,k],"")
}
profili[j]<-paste(profili[j],")")
}
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
cat("No fitted method available","\n")
}
}
if (!is.null(W) & is.null(Y)){
# W<-as.matrix(ellipsis$W)
if (NCOL(W)==1 && length(unique(W))==2){
pai<-stime[1]; gama<-stime[2:length(stime)];
# nomi<-c("pai ",paste("gamma",0:(length(gama)-1),sep="_"))
wval<-list()
nw<-NCOL(W)
W<-as.matrix(W)
for (j in 1:nw){
wval[[j]]<-sort(unique(W[,j]))
}
profiles<-expand.grid(wval)
nprof<-NROW(profiles)
theorpr<-matrix(NA,nrow=m,ncol=nprof)
csivett<-c()
#csivett<-unique(logis(W,gama))
profili<-c()
for (j in 1:nprof){
profili[j]<-"("
csivett[j]<-1/(1+ exp(-gama[1]-sum(as.numeric(profiles[j,])*gama[2:length(gama)])))
theorpr[,j]<-probcub00(m,pai,csivett[j])
for (k in 1:NCOL(profiles)){
profili[j]<-paste(profili[j],"W",k,"=",profiles[j,k])
}
profili[j]<-paste(profili[j],")")
}
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
cat("No fitted method available","\n")
}
}
if (!is.null(Y) & !is.null(W)){
# Y<-as.matrix(ellipsis$Y)
# W<-as.matrix(ellipsis$W)
ny<-NCOL(Y)
nw<-NCOL(W)
if (ny==1 & nw==1 & length(unique(Y))==2 & length(unique(W))==2 ){
if (all(Y==W)){
bet<-stime[1:(ny+1)];gama<-stime[(ny+2):length(stime)];
#nomi<-c(paste("beta",0:(length(bet)-1),sep="_"),paste("gamma",0:(length(gama)-1),sep="_"))
listW<-list()
listY<-list()
Y<-as.matrix(Y)
W<-as.matrix(W)
for (j in 1:ny){
listY[[j]]<-Y[,j]
}
for (j in 1:nw){
listW[[j]]<-W[,j]
}
eqy<-eqw<-c()
for (j in 1:length(listY)){
for (k in 1:length(listW)){
if (all(listY[[j]]==listW[[k]])){
eqy<-c(eqy,j)
eqw<-c(eqw,k)
}
}
}
comcov<-cbind(eqy,eqw)
YW<-as.matrix(unique(t(cbind(Y,W))))
#unique restituisce le righe di un array tolte le ripetizioni
paivett<-csivett<-c()
ywval<-list()
for (j in 1:NCOL(t(YW))){
ywval[[j]]<-sort(unique(t(YW)[,j]))
}
profiles<-unique(expand.grid(ywval))
nprof<-NROW(profiles)
theorpr<-matrix(NA,nrow=m,ncol=nprof)
profili<-c()
# csivett<-unique(logis(W,gama))
# paivett<-unique(logis(Y,bet))
for (j in 1:nprof){
vett<-rep(NA,nw)
if (NROW(comcov)!=0){
vett[eqw]<-as.numeric(profiles[j,eqy])
if (nw - NROW(comcov) > 0){
vett[-eqw]<-as.numeric(profiles[j,(ny+1):NCOL(profiles)])
}
} else {
vett<-as.numeric(profiles[j,(ny+1):NCOL(profiles)])
}
profili[j]="("
for (k in 1:ny){
profili[j]<-paste(profili[j],"Y",k,"=",profiles[j,k],", ")
}
for (k in 1:nw){
profili[j]<-paste(profili[j],"W",k,"=",vett[k],", ")
}
profili[j]<-paste(profili[j],")")
csivett[j]<- 1/(1+ exp(-gama[1]-sum(vett*gama[2:length(gama)])))
paivett[j]<-1/(1+ exp(-bet[1]-sum(profiles[j,1:ny]*bet[2:length(bet)])))
theorpr[,j]<-probcub00(m,paivett[j],csivett[j])
}
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
cat("No fitted method available","\n")
}
} else {
cat("No fitted method available","\n")
}
}
}
}
####################################
profiles.CUBE<-function(object){
ellipsis<-object$ellipsis
stime<-object$estimates
m<-ellipsis[['m']]
modello<-object$formula
# EFFE<-mod$Formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
covpai<-model.matrix(modello,data=mf,rhs=1)
covcsi<-model.matrix(modello,data=mf,rhs=2)
covphi<-model.matrix(modello,data=mf,rhs=3)
if (ncol(covpai)==0){
Y<-NULL
} else {
Y<-covpai[,-1]
}
if (ncol(covcsi)==0){
W<-NULL
} else {
W<-covcsi[,-1]
}
if (ncol(covphi)==0){
Z<-NULL
} else {
Z<-covphi[,-1]
}
# Y<-ellipsis$Y
# W<-ellipsis$W
#Z<-ellipsis$Z
values<-c()
for (j in 1:m){
values[j]<-paste("R =",j)
}
if (is.null(Y) & is.null(W) & is.null(Z)){
pai<-stime[1]; csi<-stime[2]; phi<-stime[3]
nprof<-1
theorpr<-matrix(NA,nrow=m,ncol=nprof)
theorpr[,1]<- probcube(m,pai,csi,phi)
profili<-""
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else if (!is.null(W) & is.null(Y) & is.null(Z)){
if (NCOL(W)==1 && length(unique(W))==2){
pai<-stime[1]; gama<-stime[2:(length(stime)-1)]; phi<-stime[length(stime)];
# nomi<-c("pai ",paste("gamma",0:(length(gama)-1),sep="_"))
wval<-list()
W<-as.matrix(W)
nw<-NCOL(W)
for (j in 1:nw){
wval[[j]]<-sort(unique(W[,j]))
}
profiles<-expand.grid(wval)
nprof<-NROW(profiles)
theorpr<-matrix(NA,nrow=m,ncol=nprof)
csivett<-c()
#csivett<-unique(logis(W,gama))
profili<-c()
for (j in 1:nprof){
profili[j]<-"("
csivett[j]<-1/(1+ exp(-gama[1]-sum(as.numeric(profiles[j,])*gama[2:length(gama)])))
theorpr[,j]<-probcube(m,pai,csivett[j],phi)
for (k in 1:NCOL(profiles)){
profili[j]<-paste(profili[j],"W",k,"=",profiles[j,k])
}
profili[j]<-paste(profili[j],")")
}
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
cat("No fitted method available","\n")
}
} else if (!is.null(Y) & !is.null(W) & !is.null(Z)){
cat("No fitted method available","\n")
}
}
####################################
profiles.IHG<-function(object){
ellipsis<-object$ellipsis
m<-ellipsis[['m']]
values<-c()
for (j in 1:m){
values[j]<-paste("R =",j)
}
modello<-object$formula
#EFFE<-mod$Formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
covtheta<-model.matrix(modello,data=mf,rhs=1)
if (ncol(covtheta)==0){
U<-NULL
} else {
U<-covtheta[,-1]
}
stime<-object$estimates
#U<-ellipsis$U
if (is.null(U)){
nprof<-1
theta<-stime[1]
theorpr<-matrix(NA,nrow=m,ncol=nprof)
theorpr[,1]<- probihg(m,theta)
profili<-""
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
if (NCOL(U)==1 && length(unique(U))==2){
nuest<-stime
uval<-list()
U<-as.matrix(U)
nu<-NCOL(U)
for (j in 1:nu){
uval[[j]]<-sort(unique(U[,j]))
}
profiles<-expand.grid(uval)
nprof<-NROW(profiles)
theorpr<-matrix(NA,nrow=m,ncol=nprof)
thetavett<-c()
#csivett<-unique(logis(W,gama))
profili<-c()
for (j in 1:nprof){
profili[j]<-"("
thetavett[j]<-1/(1+ exp(-nuest[1]-sum(as.numeric(profiles[j,])*nuest[2:length(nuest)])))
theorpr[,j]<-probihg(m,thetavett[j])
for (k in 1:NCOL(profiles)){
profili[j]<-paste(profili[j],"U",k,"=",profiles[j,k])
}
profili[j]<-paste(profili[j],")")
}
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
cat("No fitted method available","\n")
}
}
}
####################################
profiles.CUSH<-function(object,...){
ellipsis<-object$ellipsis
stime<-object$estimates
m<-ellipsis[['m']]
# X<-ellipsis$X
shelter<-ellipsis$shelter
values<-c()
for (j in 1:m){
values[j]<-paste("R =",j)
}
modello<-object$formula
# EFFE<-mod$Formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
covshe<-model.matrix(modello,data=mf,rhs=1)
if (ncol(covshe)==0){
X<-NULL
} else {
X<-covshe[,-1]
}
if (is.null(X)){
nprof<-1
delta<-stime[1]
theorpr<-matrix(NA,nrow=m,ncol=nprof)
theorpr[,1]<- probcush(m,delta,shelter)
profili<-""
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
if (NCOL(X)==1 && length(unique(X)==2)){
omega<-stime
xval<-list()
X<-as.matrix(X)
nx<-NCOL(X)
for (j in 1:nx){
xval[[j]]<-sort(unique(X[,j]))
}
profiles<-expand.grid(xval)
nprof<-NROW(profiles)
theorpr<-matrix(NA,nrow=m,ncol=nprof)
deltavett<-c()
profili<-c()
for (j in 1:nprof){
profili[j]<-"("
deltavett[j]<-1/(1+ exp(-omega[1]-sum(as.numeric(profiles[j,])*omega[2:length(omega)])))
theorpr[,j]<-probcush(m,deltavett[j],shelter)
for (k in 1:NCOL(profiles)){
profili[j]<-paste(profili[j],"X",k,"=",profiles[j,k],",")
}
profili[j]<-paste(profili[j],")")
}
dimnames(theorpr)<-list(values,profili)
return(theorpr)
} else {
cat("No fitted method available","\n")
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/fitted.R
|
#' @title Main function for CUB models with covariates for all the components
#' @description Function to estimate and validate a CUB model for given ordinal responses, with covariates for
#' explaining all the components and the shelter effect.
#' @aliases gecubpqs
#' @usage gecubpqs(ordinal,Y,W,X,shelter,theta0,maxiter,toler)
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates for explaining the uncertainty component, not including intercept
#' @param W Matrix of selected covariates for explaining the feeling component, not including intercept
#' @param X Matrix of selected covariates for explaining the shelter effect, not including intercept
#' @param shelter Category corresponding to the shelter choice
#' @param theta0 Starting values for parameters explaining the shelter effect
#' @param maxiter Maximum number of iterations allowed for running the optimization algorithm
#' @param toler Fixed error tolerance for final estimates
#' @import stats graphics
#' @return An object of the class "CUB"
#' @references
#' Piccolo D. and D'Elia A. (2008), A new approach for modelling consumers' preferences,
#' \emph{Food Quality and Preference}, \bold{18}, 247--259 \cr
#' @references
#' Iannario M. and Piccolo D. (2010), A new statistical model for the analysis of customer
#' satisfaction, #' \emph{Quality Technology and Quantity management}, \bold{7}(2) 149--168 \cr
#' Iannario M. and Piccolo D. (2012), CUB models: Statistical methods and empirical evidence, in:
#' Kenett R. S. and Salini S. (eds.), \emph{Modern Analysis of Customer Surveys: with applications using R},
#' J. Wiley and Sons, Chichester, 231--258.
#' @keywords internal
## EM algo for GECUB, #theta contains initial values for parameters
gecubpqs<-function(ordinal,Y,W,X,shelter,theta0,maxiter,toler){
Y<-as.matrix(Y); W<-as.matrix(W);X<-as.matrix(X)
s<-NCOL(X); q<-NCOL(W); p<-NCOL(Y);
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(X)==1){
X<-as.numeric(X)
}
if (ncol(W)==1){
W<-as.numeric(W)
}
tt0<-proc.time();
ndati<-NROW(ordinal);
m<-length(levels(factor(ordinal,ordered=TRUE)))
# ****************************************************************************
# ************* E-M algorithm for GECUB *************************************
# ****************************************************************************
#first step
# if (missing(theta0)){
# omega<-rep(0.1,s+1); bet<-rep(0.1,p+1); gama<-inibestgama(m,ordinal,W);
# #gama=rep(0.1,q+1); #In alternativa
# } else {
bet<-theta0[1:(p+1)]; gama<-theta0[(p+2):(p+q+2)]; omega<-theta0[(p+q+3):(p+q+s+3)];
# }
loglik<-ellegecub(ordinal,Y,W,X,bet,gama,omega,shelter);
psi<-c(omega,bet) #psi=omega|bet;
# starting iterations
nniter<-1;
while(nniter <= maxiter){
likold<-loglik;
### STEP 1: */
alpha1<-logis(X,omega);
alpha2<-(1-alpha1)*(logis(Y,bet));
alpha3<-1-alpha1-alpha2;
#/* ### STEP 2:*/
prob1<-ifelse(as.numeric(ordinal)==shelter,1,0)
prob2<-bitgama(m,factor(ordinal,ordered=TRUE),W,gama)
prob3<-1/m;
#/* ### STEP 3:*/
num1<-alpha1*prob1;
num2<-alpha2*prob2;
num3<-alpha3*prob3;
den<-num1+num2+num3;
#/* ### STEP 4:*/
ttau1<-num1/den;
ttau2<-num2/den;
ttau3<-1-ttau1-ttau2;
### STEP 5-6-7:*/
datiuno<-cbind(ttau1,ttau2,X,Y) #fissiuno=ttau1~ttau2~X~Y;
datidue<-cbind(ttau2,ordinal,W) #fissidue=ttau2~ordinal~W;
param<-psi
psioptim<-optim(param, Qunogecub, datiuno=datiuno,s=s,control=list(maxit=2000))
param<-gama;
gamaoptim<-optim(param,Q2gecub,datidue=datidue)
psinew<-psioptim$par;
gama<-gamaoptim$par;
omega<-psinew[1:(s+1)]; bet<-psinew[(s+2):(p+s+2)];
loglik<-ellegecub(ordinal,Y,W,X,bet,gama,omega,shelter);
liknew<-loglik;
testll<-abs(liknew-likold);
if (testll <= toler) break else {likold=liknew};
nniter<-nniter+1;
}
stime<-c(bet,gama,omega)
#output
loglik<-liknew;
n<-ndati
####################################################################
np<-s+p+q+3
AICGECUB<- -2*loglik+2*np;
BICGECUB<- -2*loglik+log(n)*np;
varmat<-varcovgecub(ordinal,Y,W,X,bet,gama,omega,shelter);
if (isTRUE(varmat==matrix(NA,nrow=np,ncol=np))==TRUE){
ddd<-matrix(NA,nrow=np,ncol=np)
trvarmat<-ICOMP<-NA
errstd<-wald<-pval<-rep(NA,np)
} else {
ddd<-diag(sqrt(1/diag(varmat)))
nparam<-length(stime)
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
errstd<-sqrt(diag(varmat));wald<-stime/errstd
pval<-2*(1-pnorm(abs(wald)))
cormat<-ddd%*%varmat%*%ddd
}
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'=stime,'ordinal'=ordinal,'time'=durata,
'loglik'=loglik,'niter'=nniter,
'varmat'=varmat,'BIC'=BICGECUB)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/gecubpqs.R
|
#' @title Normalized Gini heterogeneity index
#' @description Compute the normalized Gini heterogeneity
#' index for a given discrete probability distribution.
#' @usage gini(prob)
#' @aliases gini
#' @param prob Vector of probability distribution or relative frequencies
#' @keywords univar
#' @export gini
#' @seealso \code{\link{laakso}}
#' @examples
#' prob<-c(0.04,0.04,0.05,0.10,0.21,0.32,0.24)
#' gini(prob)
gini <-
function(prob){
m<-length(prob)
(1-sum(prob^2))*m/(m-1)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/gini.R
|
#' @title Main function for IHG models without covariates
#' @description Estimate and validate an IHG model without covariates for given ordinal responses.
#' @aliases ihg00
#' @usage ihg00(m, ordinal)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @return An object of the class "IHG"
#' @keywords internal
#' @details The optimization procedure is run via "optim", option method="Brent" for constrained optimization
#' (lower bound = 0, upper bound=1).
#' @import stats
#' @return An object of the class "IHG"
ihg00<-function(m,ordinal){
tt0<-proc.time()
freq<-tabulate(ordinal,nbins=m)
n<-sum(freq)
aver<-mean(ordinal)
theta<-iniihg(m,freq) ### initial value (moment estimator of theta)
estoptim<-optim(theta,effeihg,m=m,freq=freq,method="Brent",lower=0, upper=1,hessian=TRUE)
theta<-estoptim$par
errstdtheta<-1/sqrt(estoptim$hessian)
varmat<-errstdtheta^2
loglik<-loglikihg(m,freq,theta)
wald2<-(theta-1/m)/errstdtheta
pvaltheta2<-2*(1-pnorm(abs(wald2)))
##wald=theta/errstdtheta
# prima: pvaltheta1=round(2*(1-pnorm(abs(wald))),20)
# prima: pvaltheta1=round(2*(1-pnorm(abs(wald))),20)
AICIHG<- -2*loglik+2
BICIHG<- -2*loglik+log(n)
csisb<-(m-aver)/(m-1); llsb<-loglikcub00(m,freq,1,csisb);
llunif<- -n*log(m)
nonzero<-which(freq!=0)
logsat<- -n*log(n)+sum((freq[nonzero])*log(freq[nonzero]))
theorpr<-probihg(m,theta)
dissihg<-dissim(theorpr,freq/n)
pearson<-((freq-n*theorpr))/sqrt(n*theorpr)
X2<-sum(pearson^2)
relares<-(freq/n-theorpr)/theorpr
stampa<-cbind(1:m,freq/n,theorpr,pearson,relares)
LL2<-1/(1+mean((freq/(n*theorpr)-1)^2))
II2<-(loglik-llunif)/(logsat-llunif)
FF2<-1-dissihg
#####################################################
durata<-proc.time()-tt0;durata<-durata[1];
stime<-theta
results<-list('estimates'=stime, 'loglik'=loglik,'varmat'=varmat,'BIC'=BICIHG,'time'=durata)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/ihg00.R
|
#' @title Main function for IHG models with covariates
#' @description Estimate and validate an IHG model for given ordinal responses, with covariates to
#' explain the preference parameter.
#' @aliases ihgcov
#' @usage ihgcov(m, ordinal, U)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param U Matrix of selected covariates for the preference parameter
#' @return An object of the class "IHG"
#' @keywords internal
#' @details The optimization procedure is run via "optim", option method="Brent" for constrained optimization
#' (lower bound = 0, upper bound=1).
#' @import stats graphics
#' @return An object of the class "IHG"
#'
ihgcov<-function(m,ordinal,U){
tt0<-proc.time()
freq<-tabulate(ordinal,nbins=m); n<-length(ordinal);
U<-as.matrix(U)
if (ncol(U)==1){
U<-as.numeric(U)
}
theta<-iniihg(m,freq)
ncovar<-NCOL(U)
nuzero<-log(theta/(1-theta)) ### initial estimate of nu_0
nuinit<-c(nuzero,rep(0.1,ncovar)) ### initial estimate of nu vector
### maximize w.r.t. nu
nu<-nuinit
optimnu<-optim(nu,effeihgcov,ordinal=ordinal,U=U,m=m,hessian=TRUE)
#################################################################
# Computation of estimates and log-likelihood
#################################################################
nuest<-optimnu$par #nu estimates
loglik<-loglikihgcov(m,ordinal,U,nuest)
HHH<-optimnu$hessian
nparam<-length(nuest)
if (det(HHH)<=0){
warning("Variance-covariance matrix not-positive definite")
varmat<-ddd<-matrix(NA,nrow=nparam,ncol=nparam)
errst<-wald<-rep(NA,nparam)
trvarmat<-ICOMP<-NA
} else {
varmat<-solve(HHH)
errst<-sqrt(diag(varmat)) ### vector
ddd<-diag(sqrt(1/diag(varmat))) ### matrix
wald<-nuest/errst
trvarmat<-sum(diag(varmat))
ICOMP<- -2*loglik + nparam*log(trvarmat/nparam) - log(det(varmat))
}
AICIHGCOV<- -2*loglik+2*nparam
BICIHGCOV<- -2*loglik+nparam*log(n)
nomi<-c(paste("nu",0:(nparam-1),sep="_"))
stime<-nuest; errstd<-errst; wald<-wald;
pval<-2*(1-pnorm(abs(wald)))
durata<-proc.time()-tt0;durata<-durata[1];
results<-list('estimates'=stime, 'loglik'=loglik, 'varmat'=varmat,
'BIC'=BICIHGCOV,'time'=durata)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/ihgcov.R
|
#' @title Preliminary estimators for CUB models without covariates
#' @description Compute preliminary parameter estimates of a CUB model without covariates for given ordinal
#' responses. These preliminary estimators are used within the package code to start the E-M algorithm.
#' @aliases inibest
#' @usage inibest(m,freq)
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequencies of given ordinal responses
#' @export inibest
#' @return A vector \eqn{(\pi,\xi)} of the initial parameter estimates for a CUB model without covariates,
#' given the absolute frequency distribution of ordinal responses
#' @seealso \code{\link{inibestgama}}
#' @references
#'Iannario M. (2009). A comparison of preliminary estimators in a class of ordinal data models,
#' \emph{Statistica & Applicazioni}, \bold{VII}, 25--44 \cr
#' Iannario M. (2012). Preliminary estimators for a mixture model of ordinal data,
#' \emph{Advances in Data Analysis and Classification}, \bold{6}, 163--184
#' @keywords htest utilities
#' @examples
#' m<-9
#' freq<-c(10,24,28,36,50,43,23,12,5)
#' estim<-inibest(m,freq)
#' pai<-estim[1]
#' csi<-estim[2]
inibest <-
function(m,freq){
freq<-freq/sum(freq)
csi<-1+(0.5-which.max(freq))/m
ppp<-probbit(m,csi)
pai<-sqrt((sum(freq^2)-1/m)/(sum(ppp^2)-1/m))
pai<-min(pai,0.99)
ini<-as.matrix(c(pai,csi))
rownames(ini)<-list("pai","csi"); colnames(ini)<-""
return(ini)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/inibest.R
|
#' @title Naive estimates for CUBE models without covariates
#' @description Compute \emph{naive} parameter estimates of a CUBE model without covariates for given ordinal responses.
#' These preliminary estimators are used within the package code to start the E-M algorithm.
#' @aliases inibestcube
#' @usage inibestcube(m,ordinal)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @export inibestcube
#' @return A vector \eqn{(\pi, \xi ,\phi)} of parameter estimates of a CUBE model without covariates.
#' @keywords htest utilities
#' @seealso \code{\link{inibestcubecov}}, \code{\link{inibestcubecsi}}
#' @examples
#' data(relgoods)
#' m<-10
#' ordinal<-relgoods$SocialNetwork
#' estim<-inibestcube(m,ordinal) # Preliminary estimates (pai,csi,phi)
inibestcube <- function(m,ordinal){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
freq<-tabulate(ordinal,nbins=m)
inipaicsi<-inibest(m,freq)
pai<-inipaicsi[1];csi<-inipaicsi[2];
aver<-mean(ordinal)
varcamp<-mean(ordinal^2)-aver^2
varcub<-varcub00(m,pai,csi)
phist<-min(max((varcub-varcamp)/(-pai*csi*(1-csi)*(m-1)*(m-2)-varcub+varcamp),0.01),0.5)
initial<-as.matrix(c(pai,csi,phist))
rownames(initial)<-list("pai","csi","phi"); colnames(initial)<-""
return(initial)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/inibestcube.R
|
#' @title Preliminary parameter estimates for CUBE models with covariates
#' @description Compute preliminary parameter estimates for a CUBE model with covariates for all the three parameters.
#' These estimates are set as initial values to start the E-M algorithm within maximum likelihood estimation.
#' @aliases inibestcubecov
#' @usage inibestcubecov(m,ordinal,Y,W,Z)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates to explain the uncertainty parameter
#' @param W Matrix of selected covariates to explain the feeling parameter
#' @param Z Matrix of selected covariates to explain the overdispersion parameter
#' @export inibestcubecov
#' @return A vector \code{(inibet, inigama, inialpha)} of preliminary estimates of parameter vectors for
#' \eqn{\pi = \pi(\bold{\beta})}, \eqn{\xi=\xi(\bold{\gamma})}, \eqn{\phi=\phi(\bold{\alpha})}, respectively, of a CUBE model with covariates for all the three
#' parameters. In details, \code{inibet}, \code{inigama} and \code{inialpha} have length equal to NCOL(Y)+1, NCOL(W)+1 and
#' NCOL(Z)+1, respectively, to account for an intercept term for each component.
#' @keywords htest utilities
#' @seealso \code{\link{inibestcube}}, \code{\link{inibestcubecsi}}, \code{\link{inibestgama}}
#' @examples
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Tv))
#' nacovpai<-which(is.na(relgoods$Gender))
#' nacovcsi<-which(is.na(relgoods$year.12))
#' nacovphi<-which(is.na(relgoods$EducationDegree))
#' na<-union(union(naord,nacovpai),union(nacovcsi,nacovphi))
#' ordinal<-relgoods$Tv[-na]
#' Y<-relgoods$Gender[-na]
#' W<-relgoods$year.12[-na]
#' Z<-relgoods$EducationDegree[-na]
#' ini<-inibestcubecov(m,ordinal,Y,W,Z)
#' p<-NCOL(Y)
#' q<-NCOL(W)
#' inibet<-ini[1:(p+1)] # Preliminary estimates for uncertainty
#' inigama<-ini[(p+2):(p+q+2)] # Preliminary estimates for feeling
#' inialpha<-ini[(p+q+3):length(ini)] # Preliminary estimates for overdispersion
inibestcubecov <-
function(m,ordinal,Y,W,Z){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
Y<-as.matrix(Y); W<-as.matrix(W);Z<-as.matrix(Z)
if (ncol(W)==1){
W<-as.numeric(W)
}
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(Z)==1){
Z<-as.numeric(Z)
}
q<-NCOL(Y)
p<-NCOL(W)
v<-NCOL(Z)
inigama<-inibestgama(m,ordinal,W)
inicube<-inibestcube(m,ordinal)
pai<-inicube[1]
bet0<-log(pai/(1-pai))
inibet<-c(bet0,rep(0.1,q))
alpha0<-log(0.1)
inialpha<-c(alpha0,rep(0.1,v))
ini<-as.matrix(c(inibet,inigama,inialpha))
rownames(ini)<- c(paste("beta",0:NCOL(Y),sep="_"),
paste("gamma",0:NCOL(W),sep="_"),
paste("alpha",0:NCOL(Z),sep="_"))
colnames(ini)<-""
return(ini)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/inibestcubecov.R
|
#' @title Preliminary estimates of parameters for CUBE models with covariates only for feeling
#' @description Compute preliminary parameter estimates of a CUBE model with covariates only for feeling, given
#' ordinal responses. These estimates are set as initial values to start the corresponding E-M algorithm within the package.
#' @aliases inibestcubecsi
#' @usage inibestcubecsi(m,ordinal,W,starting,maxiter,toler)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of selected covariates to explain the feeling component
#' @param starting Starting values for preliminary estimation of a CUBE without covariate
#' @param maxiter Maximum number of iterations allowed for preliminary iterations
#' @param toler Fixed error tolerance for final estimates for preliminary iterations
#' @export inibestcubecsi
#' @details Preliminary estimates for the uncertainty and the overdispersion parameters are computed by short runs of EM.
#' As to the feeling component, it considers the nested CUB model with covariates and calls \code{\link{inibestgama}} to derive initial estimates for the coefficients
#' of the selected covariates for feeling.
#' @return A vector \code{(pai, gamaest, phi)}, where \code{pai} is the initial estimate for the uncertainty parameter,
#' \code{gamaest} is the vector of initial estimates for the feeling component (including an intercept term in the first entry),
#' and \code{phi} is the initial estimate for the overdispersion parameter.
#' @keywords htest utilities
#' @seealso \code{\link{inibestcube}}, \code{\link{inibestcubecov}}, \code{\link{inibestgama}}
#' @examples
#' data(relgoods)
#' isnacov<-which(is.na(relgoods$Gender))
#' isnaord<-which(is.na(relgoods$Tv))
#' na<-union(isnacov,isnaord)
#' ordinal<-relgoods$Tv[-na]; W<-relgoods$Gender[-na]
#' m<-10
#' starting<-rep(0.1,3)
#' ini<-inibestcubecsi(m,ordinal,W,starting,maxiter=100,toler=1e-3)
#' nparam<-length(ini)
#' pai<-ini[1] # Preliminary estimates for uncertainty component
#' gamaest<-ini[2:(nparam-1)] # Preliminary estimates for coefficients of feeling covariates
#' phi<-ini[nparam] # Preliminary estimates for overdispersion component
inibestcubecsi <-
function(m,ordinal,W,starting,maxiter,toler){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
gamaest<-inibestgama(m,ordinal,W)
stimacube<-GEM(Formula(ordinal~0|0|0),family="cube",starting=starting,maxiter=maxiter,toler=toler,expinform=FALSE)
param<-stimacube$estimates
elle<-length(param)
pai<-param[1]; phi<-param[elle];
iniest<-as.matrix(c(pai,gamaest,phi))
dimnames(iniest)<-list(c("pai",paste("gamma",0:NCOL(W),sep="_"),"phi"),"")
return(iniest)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/inibestcubecsi.R
|
#' @title Preliminary parameter estimates of a CUB model with covariates for feeling
#' @description Compute preliminary parameter estimates for the feeling component of a CUB model
#' fitted to ordinal responses
#' These estimates are set as initial values for parameters to start the E-M algorithm.
#' @aliases inibestgama
#' @usage inibestgama(m,ordinal,W)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of selected covariates for explaining the feeling component
#' @export inibestgama
#' @return A vector of length equal to NCOL(W)+1, whose entries are the preliminary estimates
#' of the parameters for the feeling component, including an intercept term as first entry.
#' @references Iannario M. (2008). Selecting feeling covariates in rating surveys,
#' \emph{Rivista di Statistica Applicata}, \bold{20}, 103--116 \cr
#' Iannario M. (2009). A comparison of preliminary estimators in a class of ordinal data models,
#' \emph{Statistica & Applicazioni}, \bold{VII}, 25--44 \cr
#' Iannario M. (2012). Preliminary estimators for a mixture model of ordinal data,
#' \emph{Advances in Data Analysis and Classification}, \bold{6}, 163--184
#' @seealso \code{\link{inibest}}, \code{\link{inibestcubecsi}}
#' @keywords htest utilities
#' @examples
#' data(univer)
#' m<-7; ordinal<-univer$global; cov<-univer$diploma
#' ini<-inibestgama(m,ordinal,W=cov)
inibestgama<-function(m,ordinal,W){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
WW<-cbind(1,W)
ni<-log((m-ordinal+0.5)/(ordinal-0.5))
gama<-(solve(t(WW)%*%WW))%*%(t(WW)%*%ni)
q<-NCOL(W)
listanomi<-paste("gamma",0:q,sep="_")
dimnames(gama)<-list(listanomi,"")
return(gama)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/inibestgama.R
|
#' @title Grid-based preliminary parameter estimates for CUB models
#' @description Compute the log-likelihood function of a CUB model with parameter vector \eqn{(\pi, \xi)} ranging in
#' the Cartesian product between \eqn{x} and \eqn{y}, for a given absolute frequency distribution.
#' @aliases inigrid
#' @usage inigrid(m,freq,x,y)
#' @param m Number of ordinal categories
#' @param freq Vector of length \eqn{m} of the absolute frequency distribution
#' @param x A set of values to assign to the uncertainty parameter \eqn{\pi}
#' @param y A set of values to assign to the feeling parameter \eqn{\xi}
#' @export inigrid
#' @return It returns the parameter vector corresponding to the maximum value of the log-likelihood
#' for a CUB model without covariates for given frequencies.
#' @seealso \code{\link{inibest}}
#' @keywords htest utilities
#' @examples
#' m<-9
#' x<-c(0.1,0.4,0.6,0.8)
#' y<-c(0.2, 0.5,0.7)
#' freq<-c(10,24,28,36,50,43,23,12,5)
#' ini<-inigrid(m,freq,x,y)
#' pai<-ini[1]
#' csi<-ini[2]
inigrid <-
function(m,freq,x,y){
listap<-expand.grid(x,y)
quanti<-NROW(listap)
loglik<-rep(NA,quanti)
for(j in 1:quanti){
pai<-listap[j,1]; csi<-listap[j,2];
loglik[j]<-loglikcub00(m,freq,pai,csi)
}
indice<-which.max(loglik)
ini<-as.matrix(t(listap[indice,]))
rownames(ini)<-c("pai","csi")
colnames(ini)<-""
return(ini)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/inigrid.R
|
#' @title Moment estimate for the preference parameter of the IHG distribution
#' @description Compute the moment estimate of the preference parameter of the IHG distribution.
#' This preliminary estimate is set as initial value within the optimization procedure for an IHG model
#' fitting the observed frequencies.
#' @aliases iniihg
#' @usage iniihg(m,freq)
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequency distribution of the categories
#' @export iniihg
#' @return Moment estimator of the preference parameter \eqn{\theta}.
#' @seealso \code{\link{inibest}}, \code{\link{inibestcube}}
#' @references D'Elia A. (2003). Modelling ranks using the inverse hypergeometric distribution,
#' \emph{Statistical Modelling: an International Journal}, \bold{3}, 65--78.
#' @keywords htest utilities
#' @examples
#' m<-9
#' freq<-c(70,51,48,38,29,23,12,10,5)
#' initheta<-iniihg(m,freq)
iniihg <-
function(m,freq){
aver<-sum((1:m)*freq)/sum(freq)
est<-as.matrix((m-aver)/(1+(m-2)*aver)) ### Moment estimator of theta
rownames(est)<-"theta"; colnames(est)<-""
return(est)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/iniihg.R
|
#' @title Sequence of combinatorial coefficients
#' @description Compute the sequence of binomial coefficients \eqn{{m-1}\choose{r-1}}, for \eqn{r= 1, \dots, m},
#' and then returns a vector of the same length as ordinal, whose i-th component is the corresponding binomial
#' coefficient \eqn{{m-1}\choose{r_i-1}}
#' @aliases kkk
#' @keywords internal
#' @usage kkk(m, ordinal)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
kkk <-
function(m,ordinal){
serie<-1:m
vett<-choose(m-1,serie-1)
return(vett[ordinal])
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/kkk.R
|
#' @title Normalized Laakso and Taagepera heterogeneity index
#' @description Compute the normalized Laakso and Taagepera heterogeneity index for a given
#' discrete probability distribution.
#' @aliases laakso
#' @export laakso
#' @usage laakso(prob)
#' @param prob Vector of a probability or relative frequency distribution
#' @seealso \code{\link{gini}}
#' @keywords univar
#' @references
#' Laakso, M. and Taagepera, R. (1989). Effective number of parties: a measure with application to West Europe,
#' \emph{Comparative Political Studies}, \bold{12}, 3--27.
#' @examples
#' prob<-c(0.04,0.04,0.05,0.10,0.21,0.32,0.24)
#' laakso(prob)
laakso <-
function(prob){
m<-length(prob)
1/(m/gini(prob)-m+1)}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/laakso.R
|
#' @title logLik S3 Method for class "GEM"
#' @description S3 method: logLik() for objects of class "GEM".
#' @aliases logLik.GEM
#' @method logLik GEM
#' @param object An object of class "GEM"
#' @param ... Other arguments
#' @export
#' @return Log-likelihood at the final ML estimates for parameters of the fitted GEM model.
#' @import methods
#' @seealso \code{\link{loglikCUB}}, \code{\link{loglikCUBE}}, \code{\link{GEM}}, \code{\link{loglikIHG}},
#' \code{\link{loglikCUSH}}, \code{\link{BIC}}
#' @keywords package
#' @rdname logLik.GEM
#logLik <- function(object,...) UseMethod("logLik", object)
logLik.GEM<-function(object,...){
arguments<-list(...)
digits<-arguments$digits
if (is.null(digits)){
digits<-options()$digits
}
return(round(object$loglik,digits=digits))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/logLik.R
|
#' @title The logistic transform
#' @description Create a matrix YY binding array \code{Y} with a vector of ones, placed as the first column of YY.
#' It applies the logistic transform componentwise to the standard matrix multiplication between YY and \code{param}.
#' @aliases logis
#' @usage logis(Y,param)
#' @export logis
#' @param Y A generic matrix or one dimensional array
#' @param param Vector of coefficients, whose length is NCOL(Y) + 1 (to consider also an intercept term)
#' @return Return a vector whose length is NROW(Y) and whose i-th component is the logistic function
#' at the scalar product between the i-th row of YY and the vector \code{param}.
#' @keywords utilities
#' @examples
#' n<-50
#' Y<-sample(c(1,2,3),n,replace=TRUE)
#' param<-c(0.2,0.7)
#' logis(Y,param)
logis <-
function(Y,param){
Y<-as.matrix(Y)
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
YY<-cbind(1,Y) # add 1's first column to matrix Y
val<-1/(1+exp(-YY%*%param))
if (all(dim(val)==c(1,1))){
return(as.numeric(val))
} else{
return(val)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/logis.R
|
#' @title Log-likelihood function for CUB models
#' @aliases loglikCUB
#' @description Compute the log-likelihood value of a CUB model fitting given data, with or without covariates to
#' explain the feeling and uncertainty components, or for extended CUB models with shelter effect.
#' @usage loglikCUB(ordinal,m,param,Y=0,W=0,X=0,shelter=0)
#' @export loglikCUB
#' @param ordinal Vector of ordinal responses
#' @param m Number of ordinal categories
#' @param param Vector of parameters for the specified CUB model
#' @param Y Matrix of selected covariates to explain the uncertainty component (default: no covariate is included
#' in the model)
#' @param W Matrix of selected covariates to explain the feeling component (default: no covariate is included
#' in the model)
#' @param X Matrix of selected covariates to explain the shelter effect (default: no covariate is included
#' in the model)
#' @param shelter Category corresponding to the shelter choice (default: no shelter effect is included in the
#' model)
#' @details If no covariate is included in the model, then \code{param} should be given in the form \eqn{(\pi,\xi)}.
#' More generally, it should have the form \eqn{(\bold{\beta,\gamma)}} where,
#' respectively, \eqn{\bold{\beta}} and \eqn{\bold{\gamma}} are the vectors of
#' coefficients explaining the uncertainty and the feeling components, with length NCOL(Y)+1 and
#' NCOL(W)+1 to account for an intercept term in the first entry. When shelter effect is considered, \code{param} corresponds
#' to the first possibile parameterization and hence should be given as \code{(pai1,pai2,csi)}.
#' No missing value should be present neither
#' for \code{ordinal} nor for covariate matrices: thus, deletion or imputation procedures should be preliminarily run.
#' @seealso \code{\link{logLik}}
#' @keywords htest
#' @examples
#' ## Log-likelihood of a CUB model with no covariate
#' m<-9; n<-300
#' pai<-0.6; csi<-0.4
#' ordinal<-simcub(n,m,pai,csi)
#' param<-c(pai,csi)
#' loglikcub<-loglikCUB(ordinal,m,param)
#' ##################################
#' ## Log-likelihood of a CUB model with covariate for uncertainty
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Physician))
#' nacov<-which(is.na(relgoods$Gender))
#' na<-union(naord,nacov)
#' ordinal<-relgoods$Physician[-na]; Y<-relgoods$Gender[-na]
#' bbet<-c(-0.81,0.93); ccsi<-0.2
#' param<-c(bbet,ccsi)
#' loglikcubp0<-loglikCUB(ordinal,m,param,Y=Y)
#' #######################
#' ## Log-likelihood of a CUB model with covariate for feeling
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Physician))
#' nacov<-which(is.na(relgoods$Gender))
#' na<-union(naord,nacov)
#' ordinal<-relgoods$Physician[-na]; W<-relgoods$Gender[-na]
#' pai<-0.44; gama<-c(-0.91,-0.7)
#' param<-c(pai,gama)
#' loglikcub0q<-loglikCUB(ordinal,m,param,W=W)
#' #######################
#' ## Log-likelihood of a CUB model with covariates for both parameters
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Walking))
#' nacovpai<-which(is.na(relgoods$Gender))
#' nacovcsi<-which(is.na(relgoods$Smoking))
#' na<-union(naord,union(nacovpai,nacovcsi))
#' ordinal<-relgoods$Walking[-na]
#' Y<-relgoods$Gender[-na]; W<-relgoods$Smoking[-na]
#' bet<-c(-0.45,-0.48); gama<-c(-0.55,-0.43)
#' param<-c(bet,gama)
#' loglikcubpq<-loglikCUB(ordinal,m,param,Y=Y,W=W)
#' #######################
#' ### Log-likelihood of a CUB model with shelter effect
#' m<-7; n<-400
#' pai<-0.7; csi<-0.16; delta<-0.15
#' shelter<-5
#' ordinal<-simcubshe(n,m,pai,csi,delta,shelter)
#' pai1<- pai*(1-delta); pai2<-1-pai1-delta
#' param<-c(pai1,pai2,csi)
#' loglik<-loglikCUB(ordinal,m,param,shelter=shelter)
loglikCUB<-function(ordinal,m,param,Y=0,W=0,X=0,shelter=0){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
freq<-tabulate(ordinal,nbins=m)
ry<-NROW(Y); rw<-NROW(W); rx<-NROW(X); shelter<-as.numeric(shelter)
if(shelter!=0){
if (ry==1 & rw==1 & rx==1){
pai1<-param[1]
pai2<-param[2]
csi<-param[3]
loglik<-loglikcubshe(m,freq,pai1,pai2,csi,shelter)
} else if (ry!=1 & rw !=1 & rx !=1){
Y<-as.matrix(Y); W<-as.matrix(W);X<-as.matrix(X)
if (ncol(W)==1){
W<-as.numeric(W)
}
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(X)==1){
X<-as.numeric(X)
}
ncy<-NCOL(Y); ncw<-NCOL(W); ncx<-NCOL(X)
bet<-param[1:(ncy+1)]; gama<-param[(ncy+2):(ncy+ncw+2)]; omega<-param[(ncy+ncw+3):(ncy+ncw+ncx+3)];
loglik<-ellegecub(ordinal,Y,W,X,bet,gama,omega,shelter)
} else{
cat("Wrong variables specification")
loglik<-NULL
}
}else{
if(ry==1 & rw==1 & rx==1) {
pai<-param[1]
csi<-param[2]
loglik<-loglikcub00(m,freq,pai,csi)
}
if(ry!=1 & rw==1 & rx==1) {
Y<-as.matrix(Y)
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
ncy<-NCOL(Y)
bbet<-param[1:(ncy+1)]
ccsi<-param[length(param)]
loglik<-loglikcubp0(m,ordinal,Y,bbet,ccsi)
}
if(ry==1 & rw!=1 & rx==1) {
pai<-param[1]
gama<-param[2:length(param)]
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
loglik<-loglikcub0q(m,ordinal,W,pai,gama)
}
if(ry!=1 & rw!=1& rx==1) {
ncy<-NCOL(Y)
Y<-as.matrix(Y)
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
bet<-param[1:(ncy+1)]
gama<-param[(ncy+2):length(param)]
loglik<-loglikcubpq(m,ordinal,Y,W,bet,gama)
}
}
return(loglik)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikCUB.R
|
#' @title Log-likelihood function for CUSH models
#' @aliases loglikCUSH
#' @description Compute the log-likelihood function for CUSH models with or without covariates
#' to explain the shelter effect.
#' @usage loglikCUSH(ordinal,m,param,shelter,X=0)
#' @export loglikCUSH
#' @param ordinal Vector of ordinal responses
#' @param m Number of ordinal categories
#' @param param Vector of parameters for the specified CUSH model
#' @param shelter Category corresponding to the shelter choice
#' @param X Matrix of selected covariates to explain the shelter effect (default: no covariate
#' is included in the model)
#' @details If no covariate is included in the model, then \code{param} is the estimate of the shelter
#' parameter (delta), otherwise \code{param} has length equal to NCOL(X) + 1 to account for an intercept
#' term (first entry). No missing value should be present neither for \code{ordinal} nor for \code{X}.
#' @seealso \code{\link{GEM}}, \code{\link{logLik}}
#' @keywords htest
#' @examples
#' ## Log-likelihood of CUSH model without covariates
#' n<-300
#' m<-7
#' shelter<-2; delta<-0.4
#' ordinal<-simcush(n,m,delta,shelter)
#' loglik<-loglikCUSH(ordinal,m,param=delta,shelter)
#' #####################
#' ## Log-likelihood of CUSH model with covariates
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$SocialNetwork))
#' nacov<-which(is.na(relgoods$Gender))
#' na<-union(nacov,naord)
#' ordinal<-relgoods$SocialNetwork[-na]; cov<-relgoods$Gender[-na]
#' omega<-c(-2.29, 0.62)
#' loglikcov<-loglikCUSH(ordinal,m,param=omega,shelter=1,X=cov)
loglikCUSH<-function(ordinal,m,param,shelter,X=0){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
nx<-NROW(X)
if (nx==1){
delta<-param
loglik<-loglikcush00(m,ordinal,delta,shelter)
} else {
omega<-param
X<-as.matrix(X)
if (ncol(X)==1){
X<-as.numeric(X)
}
loglik<-loglikcushcov(m,ordinal,X,omega,shelter)
}
return(loglik)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikCUSH.R
|
#' @title Log-likelihood function of a CUB model without covariates
#' @description Compute the log-likelihood function of a CUB model without covariates for a given
#' absolute frequency distribution.
#' @aliases loglikcub00
#' @usage loglikcub00(m, freq, pai, csi)
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequency distribution
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @keywords internal
#'
loglikcub00 <-
function(m,freq,pai,csi){t(freq)%*%log(probcub00(m,pai,csi))}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcub00.R
|
#' @title Log-likelihood function of a CUB model with covariates for the feeling component
#' @description Compute the log-likelihood function of a CUB model fitting ordinal data, with \eqn{q}
#' covariates for explaining the feeling component.
#' @aliases loglikcub0q
#' @usage loglikcub0q(m, ordinal, W, pai, gama)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of selected covariates for explaining the feeling component
#' @param pai Uncertainty parameter
#' @param gama Vector of parameters for the feeling component, with length NCOL(W) + 1 to account for
#' an intercept term (first entry of gama)
#' @keywords internal
#'
loglikcub0q <-
function(m,ordinal,W,pai,gama){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
W<-as.matrix(W)
probn<-probcub0q(m,ordinal,W,pai,gama)
sum(log(probn))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcub0q.R
|
#' @title Log-likelihood function of a CUBE model without covariates
#' @aliases loglikcube
#' @description Compute the log-likelihood function of a CUBE model without covariates fitting
#' the given absolute frequency distribution.
#' @usage loglikcube(m,freq,pai,csi,phi)
#' @keywords internal
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequency distribution
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @param phi Overdispersion parameter
loglikcube <-
function(m,freq,pai,csi,phi){t(freq)%*%log(probcube(m,pai,csi,phi))}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcube.R
|
#' @title Log-likelihood function for CUBE models
#' @aliases loglikCUBE
#' @description Compute the log-likelihood function for CUBE models. It is possible to include
#' covariates in the model for explaining the feeling component or all the three parameters.
#' @usage loglikCUBE(ordinal,m,param,Y=0,W=0,Z=0)
#' @export loglikCUBE
#' @param ordinal Vector of ordinal responses
#' @param m Number of ordinal categories
#' @param param Vector of parameters for the specified CUBE model
#' @param Y Matrix of selected covariates to explain the uncertainty component (default: no covariate is included
#' in the model)
#' @param W Matrix of selected covariates to explain the feeling component (default: no covariate is included
#' in the model)
#' @param Z Matrix of selected covariates to explain the overdispersion component (default: no covariate is included
#' in the model)
#' @details If no covariate is included in the model, then \code{param} has the form \eqn{(\pi,\xi,\phi)}. More generally,
#' it has the form \eqn{(\bold{\beta,\gamma,\alpha)}} where, respectively, \eqn{\bold{\beta}},\eqn{\bold{\gamma}}, \eqn{\bold{\alpha}}
#' are the vectors of coefficients explaining the uncertainty, the feeling and the overdispersion components, with length NCOL(Y)+1,
#' NCOL(W)+1, NCOL(Z)+1 to account for an intercept term in the first entry. No missing value should be present neither
#' for \code{ordinal} nor for covariate matrices: thus, deletion or imputation procedures should be preliminarily run.
#' @seealso \code{\link{logLik}}
#' @keywords htest
#' @examples
#' #### Log-likelihood of a CUBE model with no covariate
#' m<-7; n<-400
#' pai<-0.83; csi<-0.19; phi<-0.045
#' ordinal<-simcube(n,m,pai,csi,phi)
#' loglik<-loglikCUBE(ordinal,m,param=c(pai,csi,phi))
#' ##################################
#' #### Log-likelihood of a CUBE model with covariate for feeling
#' data(relgoods)
#' m<-10
#' nacov<-which(is.na(relgoods$BirthYear))
#' naord<-which(is.na(relgoods$Tv))
#' na<-union(nacov,naord)
#' age<-2014-relgoods$BirthYear[-na]
#' lage<-log(age)-mean(log(age))
#' ordinal<-relgoods$Tv[-na]; W<-lage
#' pai<-0.63; gama<-c(-0.61,-0.31); phi<-0.16
#' param<-c(pai,gama,phi)
#' loglik<-loglikCUBE(ordinal,m,param,W=W)
#' ########## Log-likelihood of a CUBE model with covariates for all parameters
#' Y<-W<-Z<-lage
#' bet<-c(0.18, 1.03); gama<-c(-0.6, -0.3); alpha<-c(-2.3,0.92)
#' param<-c(bet,gama,alpha)
#' loglik<-loglikCUBE(ordinal,m,param,Y=Y,W=W,Z=Z)
loglikCUBE <-
function(ordinal,m,param,Y=0,W=0,Z=0){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
ry<-NROW(Y); rw<-NROW(W); rz<-NROW(Z);
freq<-tabulate(ordinal,nbins=m)
if(ry==1 & rw==1 & rz==1) {
pai<-param[1]; csi<-param[2]; phi<-param[3];
loglik<-loglikcube(m,freq,pai,csi,phi)
} else if (ry==1 & rz==1 & rw >1){
ncw<-NCOL(W)
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
pai<-param[1]; gama<-param[2:(ncw+2)]; phi<-param[length(param)];
loglik<-loglikcubecsi(m,ordinal,W,pai,gama,phi)
} else if(ry>1 & rz>1 & rw >1){
Y<-as.matrix(Y); W<-as.matrix(W); Z<-as.matrix(Z)
if (ncol(W)==1){
W<-as.numeric(W)
}
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(Z)==1){
Z<-as.numeric(Z)
}
ncy<-NCOL(Y)
ncw<-NCOL(W)
bet<-param[1:(ncy+1)]; gama<-param[(ncy+2):(ncy+ncw+2)]; alpha<-param[(ncy+ncw+3):length(param)];
loglik<-loglikcubecov(m,ordinal,Y,W,Z,bet,gama,alpha)
} else {
cat("CUBE models not available for this variables specification")
}
return(loglik)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcube_1.R
|
#' @title Log-likelihood function of a CUBE model with covariates
#' @aliases loglikcubecov
#' @description Compute the log-likelihood function of a CUBE model for ordinal responses,
#' with covariates for explaining all the three parameters.
#' @usage loglikcubecov(m, ordinal, Y, W, Z, bet, gama, alpha)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of covariates for explaining the uncertainty component
#' @param W Matrix of covariates for explaining the feeling component
#' @param Z Matrix of covariates for explaining the overdispersion component
#' @param bet Vector of parameters for the uncertainty component, with length equal to
#' NCOL(Y) + 1 to account for an intercept term (first entry of bet)
#' @param gama Vector of parameters for the feeling component, with length equal to
#' NCOL(W) + 1 to account for an intercept term (first entry of gama)
#' @param alpha Vector of parameters for the overdispersion component, with length equal to
#' NCOL(Z) + 1 to account for an intercept term (first entry of alpha)
#' @keywords internal
loglikcubecov <-
function(m,ordinal,Y,W,Z,bet,gama,alpha){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
Y<-as.matrix(Y); W<-as.matrix(W); Z<-as.matrix(Z)
paivett<-logis(Y,bet); csivett<-logis(W,gama);
phivett<-1/(-1+ 1/(logis(Z,alpha)))
probi<-paivett*(betabinomial(m,ordinal,csivett,phivett)-1/m)+1/m
return(sum(log(probi)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcubecov.R
|
#' @title Log-likelihood function of CUBE model with covariates only for feeling
#' @aliases loglikcubecsi
#' @description
#' Compute the log-likelihood function of a CUBE model for ordinal data with subjects'
#' covariates only for feeling.
#' @usage loglikcubecsi(m, ordinal, W, pai, gama, phi)
#' @keywords internal
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of covariates for explaining the feeling component
#' @param pai Uncertainty parameter
#' @param gama Vector of parameters for the feeling component, with length
#' equal to NCOL(W) + 1 to account for an intercept term (first entry of gama)
#' @param phi Overdispersion parameter
#' @seealso internal
loglikcubecsi <-
function(m,ordinal,W,pai,gama,phi){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
W<-as.matrix(W)
csivett<-logis(W,gama)
probi<-pai*(betabinomialcsi(m,ordinal,csivett,phi)-1/m)+1/m
return(sum(log(probi)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcubecsi.R
|
#' @title Log-likelihood function of CUBE models for ordinal data
#' @aliases loglikcuben
#' @description Compute the log-likelihood function of a CUBE model
#' without covariates for ordinal responses, possibly with different
#' vectors of parameters for each observation.
#' @usage loglikcuben(m, ordinal, assepai, assecsi, assephi)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param assepai Vector of uncertainty parameters for the given
#' observations (with the same length as ordinal)
#' @param assecsi Vector of feeling parameters for the given observations
#' (with the same length as ordinal)
#' @param assephi Vector of overdispersion parameters for the given
#' observations (with the same length as ordinal)
#' @export loglikcuben
#' @seealso \code{\link{loglikCUBE}}
#' @keywords internal
#' @examples
#' m<-8
#' n0<-230; n1<-270
#' bet<-c(-1.5,1.2)
#' gama<-c(0.5,-1.2)
#' alpha<-c(-1.2,-0.5)
#' pai0<-1/(1+exp(-bet[1])); csi0<-1/(1+exp(-gama[1])); phi0<-exp(alpha[1])
#' ordinal0<-simcube(n0,m,pai0,csi0,phi0)
#' pai1<-1/(1+exp(-sum(bet))); csi1<-1/(1+exp(-sum(gama))); phi1<-exp(sum(alpha))
#' ordinal1<-simcube(n1,m,pai1,csi1,phi1)
#' ordinal<-c(ordinal0,ordinal1)
#' assepai<-c(rep(pai0,n0),rep(pai1,n1))
#' assecsi<-c(rep(csi0,n0),rep(csi1,n1))
#' assephi<-c(rep(phi0,n0),rep(phi1,n1))
#' lli<-loglikcuben(m,ordinal,assepai,assecsi,assephi)
loglikcuben <-
function(m,ordinal,assepai,assecsi,assephi){
n<-length(ordinal)
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
prob<-matrix(NA,nrow=n,ncol=m)
pconi<-rep(NA,n)
for (i in 1:n){
prob[i,]<-t(probcube(m,assepai[i],assecsi[i],assephi[i]))
pconi[i]<-prob[i,ordinal[i]]
}
return(sum(log(pconi)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcuben.R
|
#' @title Log-likelihood function of a CUB model with covariates for the uncertainty component
#' @description Compute the log-likelihood function of a CUB model fitting ordinal responses with covariates
#' for explaining the uncertainty component.
#' @aliases loglikcubp0
#' @usage loglikcubp0(m, ordinal, Y, bbet, ccsi)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates for explaining the uncertainty component
#' @param bbet Vector of parameters for the uncertainty component, with length equal to
#' NCOL(Y)+1 to account for an intercept term (first entry of bbet)
#' @param ccsi Feeling parameter
#' @keywords internal
loglikcubp0 <-
function(m,ordinal,Y,bbet,ccsi){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
Y<-as.matrix(Y)
prob<-probbit(m,ccsi)
probn<-prob[ordinal]
eta<-logis(Y,bbet)
return(sum(log(eta*(probn-1/m)+1/m)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcubp0.R
|
#' @title Log-likelihood function of a CUB model with covariates for both feeling and uncertainty
#' @description Compute the log-likelihood function of a CUB model fitting ordinal data
#' with covariates for explaining both the feeling and the uncertainty components.
#' @aliases loglikcubpq
#' @usage loglikcubpq(m, ordinal, Y, W, bet, gama)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of selected covariates for explaining the uncertainty component
#' @param W Matrix of selected covariates for explaining the feeling component
#' @param bet Vector of parameters for the uncertainty component, with length equal to
#' NCOL(Y)+1 to account for an intercept term (first entry of bbet)
#' @param gama Vector of parameters for the feeling component, whose length equals
#' NCOL(W) + 1 to account for an intercept term (first entry of gama)
#' @keywords internal
loglikcubpq <-
function(m,ordinal,Y,W,bet,gama){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
Y<-as.matrix(Y); W<-as.matrix(W)
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(W)==1){
W<-as.numeric(W)
}
probn<-probcubpq(m,ordinal,Y,W,bet,gama)
return(sum(log(probn)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcubpq.R
|
#' @title Log-likelihood of a CUB model with shelter effect
#' @aliases loglikcubshe
#' @description Compute the log-likelihood of a CUB model with a shelter effect
#' for the given absolute frequency distribution.
#' @usage loglikcubshe(m, freq, pai1, pai2, csi, shelter)
#' @keywords internal
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequency distribution
#' @param pai1 Mixing coefficient for the shifted Binomial component of the mixture distribution
#' @param pai2 Mixing coefficient for the discrete Uniform component of the mixture distribution
#' @param csi Feeling parameter
#' @param shelter Category corresponding to the shelter choice
loglikcubshe <-
function(m,freq,pai1,pai2,csi,shelter)
{t(freq)%*%log(probcubshe1(m,pai1,pai2,csi,shelter))}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcubshe.R
|
#' @title Log-likelihood function for a CUSH model without covariates
#' @aliases loglikcush00
#' @description Compute the log-likelihood function for a CUSH model
#' without covariate for the given ordinal responses.
#' @usage loglikcush00(m,ordinal,delta,shelter)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param delta Shelter parameter
#' @param shelter Category corresponding to the shelter choice
#' @seealso \code{\link{GEM}}
#' @keywords internal
loglikcush00<-function(m,ordinal,delta,shelter){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
n<-length(ordinal);
freq<-tabulate(ordinal,nbins=m)
fc<-freq[shelter]/n
loglik<-n*((1-fc)*log(1-delta)+fc*log(1+(m-1)*delta)-log(m))
return(loglik)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcush00.R
|
#' @title Log-likelihood function for a CUSH model with covariates
#' @aliases loglikcushcov
#' @description Compute the log-likelihood function for a CUSH model
#' with covariates for the given ordinal responses.
#' @usage loglikcushcov(m, ordinal, X, omega, shelter)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param X Matrix of selected covariates for explaining the shelter parameter
#' @param omega Vector of parameters for explaining the shelter effect,
#' with length equal to NCOL(X)+1 to account for an intercept term (first entry of omega)
#' @param shelter Category corresponding to the shelter choice
#' @keywords internal
#'
loglikcushcov <-function(m,ordinal,X,omega,shelter){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
X<-as.matrix(X)
deltavett<-logis(X,omega)
dummy<-ifelse(ordinal==shelter,1,0)
probi<-deltavett*(dummy-1/m)+1/m
return(sum(log(probi)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikcushcov.R
|
#' @title Log-likelihood function for an IHG model without covariates
#' @aliases loglikihg
#' @description Compute the log-likelihood function for an IHG model without covariates for
#' the given absolute frequency distribution.
#' @usage loglikihg(m, freq, theta)
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequency distribution
#' @param theta Preference parameter
#' @keywords internal
loglikihg <-
function(m,freq,theta){
t(freq)%*%log(probihg(m,theta))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikihg.R
|
#' @title Log-likelihood function for IHG models
#' @aliases loglikIHG
#' @description Compute the log-likelihood function for IHG models with or without covariates
#' to explain the preference parameter.
#' @usage loglikIHG(ordinal,m,param,U=0)
#' @export loglikIHG
#' @param ordinal Vector of ordinal responses
#' @param m Number of ordinal categories
#' @param param Vector of parameters for the specified IHG model
#' @param U Matrix of selected covariates to explain the preference parameter (default: no covariate is included
#' in the model)
#' @details If no covariate is included in the model, then \code{param} is the estimate of the preference
#' parameter (\eqn{theta}), otherwise \code{param} has length equal to NCOL(U) + 1 to account for an intercept
#' term (first entry). No missing value should be present neither for \code{ordinal} nor for \code{U}.
#' @seealso \code{\link{GEM}}, \code{\link{logLik}}
#' @keywords htest
#' @examples
#' #### Log-likelihood of an IHG model with no covariate
#' m<-10; theta<-0.14; n<-300
#' ordinal<-simihg(n,m,theta)
#' loglik<-loglikIHG(ordinal,m,param=theta)
#' ##################################
#' #### Log-likelihood of a IHG model with covariate
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$HandWork))
#' nacov<-which(is.na(relgoods$Gender))
#' na<-union(naord,nacov)
#' ordinal<-relgoods$HandWork[-na]; U<-relgoods$Gender[-na]
#' nu<-c(-1.55,-0.11) # first entry: intercept term
#' loglik<-loglikIHG(ordinal,m,param=nu,U=U); loglik
loglikIHG <-
function(ordinal,m,param,U=0){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
nu<-NROW(U)
if (nu==1){
theta<-param
freq<-tabulate(ordinal,nbins=m)
loglik<-loglikihg(m,freq,theta)
} else {
nu<-param
U<-as.matrix(U)
if (ncol(U)==1){
U<-as.numeric(U)
}
loglik<-loglikihgcov(m,ordinal,U,nu)
}
return(loglik)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikihg_1.R
|
#' @title Log-likelihood function for the IHG model with covariates
#' @aliases loglikihgcov
#' @description Compute the log-likelihood function for the IHG model
#' with covariates to explain the preference parameter.
#' @usage loglikihgcov(m, ordinal, U, nu)
#' @keywords internal
#' @seealso loglikIHG
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param U Matrix of selected covariates for explaining the preference parameter
#' @param nu Vector of coefficients for covariates, whose length equals NCOL(U)+1 to include
#' an intercept term in the model (first entry of nu)
loglikihgcov <-
function(m,ordinal,U,nu){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
U<-as.matrix(U)
sum(log(probihgcovn(m,ordinal,U,nu)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/loglikihgcov.R
|
#' @title Logarithmic score
#' @description Compute the logarithmic score of a CUB model with covariates both for the uncertainty
#' and the feeling parameters.
#' @aliases logscore
#' @export logscore
#' @usage logscore(m,ordinal,Y,W,bet,gama)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of covariates for explaining the uncertainty component
#' @param W Matrix of covariates for explaining the feeling component
#' @param bet Vector of parameters for the uncertainty component, with length NCOL(Y)+1
#' to account for an intercept term (first entry of \code{bet})
#' @param gama Vector of parameters for the feeling component, with length NCOL(W)+1
#' to account for an intercept term (first entry of \code{gama})
#' @details No missing value should be present neither
#' for \code{ordinal} nor for covariate matrices: thus, deletion or imputation procedures should be
#' preliminarily run.
#' @references
#' Tutz, G. (2012). \emph{Regression for Categorical Data}, Cambridge University Press, Cambridge
#' @keywords htest
#' @examples
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Walking))
#' nacovpai<-which(is.na(relgoods$Gender))
#' nacovcsi<-which(is.na(relgoods$Smoking))
#' na<-union(naord,union(nacovpai,nacovcsi))
#' ordinal<-relgoods$Walking[-na]
#' Y<-relgoods$Gender[-na]
#' W<-relgoods$Smoking[-na]
#' bet<-c(-0.45,-0.48)
#' gama<-c(-0.55,-0.43)
#' logscore(m,ordinal,Y=Y,W=W,bet,gama)
logscore <-
function(m,ordinal,Y,W,bet,gama){
pr<-as.numeric(probcubpq(m,ordinal,Y,W,bet,gama))
return(-2*sum(log(pr)))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/logscore.R
|
#' @title Plot facilities for GEM objects
#' @description Plot facilities for objects of class "GEM".
#' @aliases makeplot
#' @param object An object of class "GEM"
#' @export
#' @details Returns a plot comparing fitted
#' probabilities and observed relative frequencies for GEM models without covariates. If only one
#' explanatory dichotomous variable is included in the model for one or all components,
#' then the function returns a plot comparing the distributions of the responses conditioned to
#' the value of the covariate.
#' @keywords models device package
#' @seealso \code{\link{cubvisual}}, \code{\link{cubevisual}}, \code{\link{cubshevisual}},
#' \code{\link{multicub}}, \code{\link{multicube}}
makeplot<-function(object){
if (object$family=="CUB"){
makeplotCUB(object)
}
if (object$family=="CUBE"){
makeplotCUBE(object)
}
if (object$family=="IHG"){
makeplotIHG(object)
}
if (object$family=="CUSH"){
makeplotCUSH(object)
}
}
makeplotCUB<-function(object){
ellipsis<-object$ellipsis
ordinal<-object$ordinal
family<-object$family
m <- ellipsis[['m']]
n<-length(ordinal)
modello<-object$formula
#EFFE<-mod$Formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
#covpai<-model.matrix(Formula,data=data,rhs=1)
#covcsi<-model.matrix(Formula,data=data,rhs=2)
covpai<-model.matrix(modello,data=mf,rhs=1)
covcsi<-model.matrix(modello,data=mf,rhs=2)
covshe<-model.matrix(modello,data=mf,rhs=3)
if (ncol(covpai)==0){
Y<-NULL
} else {
Y<-covpai[,-1]
}
if (ncol(covcsi)==0){
W<-NULL
} else {
W<-covcsi[,-1]
}
if (ncol(covshe)==0){
X<-NULL
} else {
X<-covshe[,-1]
}
stime<-round(object$estimates,5);
if (!is.null(ellipsis$shelter)){
if (is.null(W) & is.null(Y) & is.null(X)){
theorpr<-fitted(object)
pai1<-stime[1];pai2<-stime[2];csi<-stime[3]
delta<-1-pai1-pai2
paistar<-pai1/(pai1+pai2)
freq<-tabulate(ordinal,nbins=m)
dissshe<-dissim(freq/n,theorpr[,1])
plot(cbind(1:m,1:m),cbind(theorpr[,1],(freq/n)),
main=paste("CUB with shelter effect"," (Diss =",round(dissshe,digits=4),")"),
xlim=c(1,m),ylim=c(0.0,1.1*max(theorpr[,1],(freq/n))),
xlab="Ordinal values of R=1,2,...,m",
ylab=expression(paste("Observed freq. (dots) and fitted prob. (circles)")));
points(1:m,theorpr[,1],pch=21,cex=1.2,lwd=2.0,type="b",lty=3);
points(1:m,freq/n,pch=16,cex=1.2);
abline(h=0);
} else {
cat("No built-in plot method for this variables specifications: see multicub() and cubshevisual()","\n")
}
} else {
if ( is.null(W) & is.null(Y) & is.null(X)){
theorpr<-fitted(object)
#freq<-matrix(NA,nrow=m,ncol=nprof)
freq<-tabulate(ordinal,nbins=m)
stringtitle<-"CUB model";
thpr<-theorpr[,1]
dissimi<-dissim(thpr,freq/n)
#par(mfrow=c(2,1))
plot(cbind(1:m,1:m),cbind(thpr,(freq/n)),las=1,
main=paste(stringtitle, " (Diss =",round(dissimi,digits=4),")"),
xlim=c(1,m),ylim=c(0.0,1.1*max(thpr,(freq/n))),
xlab="Ordinal values of R=1,2,...,m",
ylab=expression(paste("Observed relative frequencies (dots) and fitted probabilities (circles)")));
###
points(1:m,thpr,pch=21,cex=1.5,lwd=2.0,type="b",lty=3); ### ex pch=8,col="red"
points(1:m,freq/n,pch=16,cex=1.25,lwd=1.5);
abline(h=0);
# cubvisual(m,ordinal,labelpoint="estim")
# par(mfrow=c(1,1))
}
if (is.null(W) & !is.null(Y) & is.null(X)) {
#Y<-ellipsis$Y
if (length(unique(Y))==2){
theorpr<-fitted(object)
prob0<-theorpr[,1]
prob1<-theorpr[,2]
maxpr<-max(prob0,prob1)
plot(1:m,prob0,ylim=c(0.0,1.1*maxpr),cex.main=0.9,las=1,
main="CUB distributions, given pai-covariate=0, 1",
cex=1.2,xlab="Ordinal values of R=1,2,...,m",
ylab="Prob(R|D=0) (circles) and Prob(R|D=1) (dots)",pch=1,lty=1,type="b");
lines(1:m,prob1,cex=1.2,pch=19,lty=2,type="b");
abline(h=0);
} else {
cat("No built-in plot method for this variables specifications: see multicub() and cubvisual()","\n")
# multicub(listaord,as.list(rep(m,nprof)),labelpoints = profili)
}
}
if (!is.null(W) & is.null(Y) & is.null(X)){
#W<-as.matrix(ellipsis$W)
if (NCOL(W)==1 && length(unique(W))==2){
theorpr<-fitted(object)
prob0<-theorpr[,1]
prob1<-theorpr[,2]
maxpr<-max(prob0,prob1)
plot(1:m,prob0,ylim=c(0.0,1.1*maxpr),cex.main=0.9,las=1,
main="CUB distributions, given csi-covariate=0, 1",
cex=1.2,xlab="Ordinal values of R=1,2,...,m",
ylab="Prob(R|D=0) (circles) and Prob(R|D=1) (dots)",pch=1,lty=1,type="b");
lines(1:m,prob1,cex=1.2,pch=19,lty=2,type="b");
abline(h=0);
# multicub(listaord,as.list(rep(m,nprof)),labelpoints = profili)
} else {
cat("No built-in plot method for this variables specifications: see multicub() and cubvisual()","\n")
}
}
if(!is.null(W) & !is.null(Y) & is.null(X)){
# Y<-as.matrix(ellipsis$Y)
# W<-as.matrix(ellipsis$W)
ny<-NCOL(Y)
nw<-NCOL(W)
if (ny==1 & nw==1 & length(unique(Y))==2 & length(unique(W))==2 ){
if (all(Y==W)){
theorpr<-fitted(object)
#par(mfrow=c(2,1))
prob0<-theorpr[,1]
prob1<-theorpr[,2]
maxpr<-max(prob0,prob1)
plot(1:m,prob0,ylim=c(0.0,1.1*maxpr),cex.lab=0.9,cex.main=0.9,las=1,
main="CUB distributions, given pai-csi covariate=0, 1",
cex=1.2,xlab="Ordinal values of R=1,2,...,m",
ylab="Prob(R|D=0) (circles) and Prob(R|D=1) (dots)",pch=1,lty=1,type="b");
lines(1:m,prob1,cex=1.2,pch=19,lty=2,type="b");
abline(h=0);
# multicub(listaord,as.list(rep(m,nprof)),labelpoints = profili)
# par(mfrow=c(1,1))
}
} else {
cat("No built-in plot method for this variables specifications: see multicub() and cubvisual()","\n")
}
# multicub(listaord,as.list(rep(m,nprof)),labelpoints = profili)
#par(mfrow=c(1,1))
}
} #chiude check su shelter
}
makeplotCUBE<-function(object){
ellipsis<-object$ellipsis
ordinal<-object$ordinal
family<-object$family
m <- ellipsis[['m']]
modello<-object$formula
# EFFE<-mod$Formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
covpai<-model.matrix(modello,data=mf,rhs=1)
covcsi<-model.matrix(modello,data=mf,rhs=2)
covphi<-model.matrix(modello,data=mf,rhs=3)
if (ncol(covpai)==0){
Y<-NULL
} else {
Y<-covpai[,-1]
}
if (ncol(covcsi)==0){
W<-NULL
} else {
W<-covcsi[,-1]
}
if (ncol(covphi)==0){
Z<-NULL
} else {
Z<-covphi[,-1]
}
n<-length(ordinal)
theorpr<-fitted(object)
freq<-tabulate(ordinal,nbins=m)
stime<-round(object$estimates,5)
# Y<-ellipsis$Y
# W<-ellipsis$W
# Z<-ellipsis$Z
theorpr<-fitted(object)
dissimcube<-dissim(theorpr,freq/n)
if (is.null(Y) & is.null(W) & is.null(Z)){
#par(mfrow=c(2,1))
stringtitle="CUBE model estimation ";
plot(cbind(1:m,1:m),cbind(theorpr,(freq/n)),las=1,cex=1.2,
main=paste(stringtitle, " (Diss =",round(dissimcube,digits=4),")"),
xlim=c(1,m),ylim=c(0.0,1.1*max(theorpr,(freq/n))),
xlab="Ordinal values of R=1,2,...,m",
ylab="Obs. relative frequencies (dots) and fitted prob. (circles)",cex.lab=0.9,cex.main=0.9);
###
points(1:m,theorpr,pch=21,cex=1.5,lwd=2.0,type="b",lty=3); ### ex pch=8,col="red"
points(1:m,freq/n,pch=16,cex=1.25,lwd=1.5);
abline(h=0);
#
} else if (is.null(Y) & !is.null(W) & is.null(Z)){
if (NCOL(W)==1 & length(unique(W))==2){
#par(mfrow=c(1,1))
pai<-stime[1]; gama<-stime[2:(length(stime)-1)]; phi<-stime[length(stime)];
vett<-as.matrix(c(0,1))
csi0<-logis(vett[1],gama); prob0<-probcube(m,pai,csi0,phi); #theorpr[,1]? (ordine)
csi1<-logis(vett[2],gama); prob1<-probcube(m,pai,csi1,phi);
maxpr<-max(prob0,prob1)
plot(1:m,prob0,ylim=c(0.0,1.1*maxpr),las=1,
main="CUBE distributions, given csi-covariate=0, 1",
cex.lab=0.9,cex.main=0.9,xlab="Ordinal values of R=1,2,...,m",
ylab="Prob(R|D=0) (circles) and Prob(R|D=1) (dots)",pch=1,lty=1,type="b");
lines(1:m,prob1,cex=1.2,pch=19,lty=2,type="b");
abline(h=0);
} else {
cat("No built-in Plot method available for this variables specification: see multicube() or cubevisual()","\n")
}
}
}
makeplotIHG<-function(object){
ellipsis<-object$ellipsis
ordinal<-object$ordinal
m <- ellipsis[['m']]
freq<-tabulate(ordinal,nbins=m)
n <-length(ordinal)
modello<-object$formula
#EFFE<-mod$Formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
covtheta<-model.matrix(modello,data=mf,rhs=1)
if (ncol(covtheta)==0){
U<-NULL
} else {
U<-covtheta[,-1]
}
#U<-ellipsis$U
if (is.null(U)){
theorpr<-fitted(object)
dissihg<-dissim(theorpr[,1],freq/n)
plot(cbind(1:m,1:m),cbind(theorpr[,1],(freq/n)),
main=paste("IHG model (without covariates)"," (Diss =",round(dissihg,digits=4),")"),
xlim=c(1,m),ylim=c(0,1.1*max(theorpr[,1],(freq/n))),las=1,
xlab="Ordinal values of R=1,2,...,m",
ylab=expression(paste("Obs. relative frequencies (dots) and fitted prob. (circles)")),
cex.lab=0.9,cex.main=0.9,cex=1.2)
points(1:m,theorpr,pch=21,cex=1.5, lwd=2.0,type="b",lty=3)
points(1:m,freq/n,pch=16,cex=1.2)
### points(shelter,theorpr[shelter]-delta,pch=8);
abline(h=0);
#################
} else {
nuest<-object$estimates
if (NCOL(U)==1 & length(unique(U))==2){
theorpr<-fitted(object)
vett<-as.matrix(c(0,1))
theta0<-logis(vett[1],nuest)
theta1<-logis(vett[2],nuest)
prob0<-probihg(m,theta0)
prob1<-probihg(m,theta1)
maxpr<-max(prob0,prob1)
plot(1:m,prob0,ylim=c(0.0,1.1*maxpr),cex.main=0.9,las=1,
main="IHG distributions, given theta-covariate=0, 1",cex.lab=0.9,cex.main=0.9,
xlab="Ordinal values of R=1,2,...,m",
ylab="Prob(R|D=0) (circles) and Prob(R|D=1) (dots)",pch=1,lty=1,type="b");
lines(1:m,prob1,cex=1.2,pch=19,lty=2,type="b");
abline(h=0);
} else {
cat("No built-in plot method available for this variables specification","\n")
}
}
}
makeplotCUSH<-function(object){
ellipsis<-object$ellipsis
ordinal<-object$ordinal
shelter<-ellipsis$shelter
m <- ellipsis[['m']]
freq<-tabulate(ordinal,nbins=m)
n <-length(ordinal)
modello<-object$formula
# EFFE<-mod$Formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
covshe<-model.matrix(modello,data=mf,rhs=1)
if (ncol(covshe)==0){
X<-NULL
} else {
X<-covshe[,-1]
}
#X<-ellipsis$X
if (is.null(X)){
theorpr<-fitted(object)
fc<-freq[shelter]/n
deltaest<-object$estimates
diss00<-dissim(theorpr[,1],freq/n)
################### GRAFICI sovrapposti #########
# par(mar=c(4,4,2.5,1)+0.1) ; ### reset standard margins
# par(mfrow=c(2,1)); ### ripristina l'area del grafico
###### Distributions
stringtitle="CUSH model (without covariates)";
plot(cbind(1:m,1:m),cbind(theorpr[,1],(freq/n)),las=1,
main=paste(stringtitle," (Diss =",round(diss00,digits=4),")"),
xlim=c(1,m),ylim=c(0.0,1.1*max(theorpr[,1],(freq/n))),
xlab="Ordinal values of R=1,2,...,m",
ylab="Obs. freq (dots) and fitted prob. (circles)",
cex.lab=0.9,cex.main=0.9,cex=1.2);
points(1:m,theorpr,pch=21,cex=1.5,lwd=2.0,type="b",lty=3);
points(1:m,freq/n,pch=16,cex=1.5,lwd=1.5);
abline(h=0);
} else {
X<-as.matrix(X)
omegaest<-object$estimates
if (NCOL(X)==1 & length(unique(X))==2){
theorpr<-fitted(object)
vett<-as.matrix(c(0,1))
delta0<-logis(vett[1],omegaest)
delta1<-logis(vett[2],omegaest)
prob0<-probcush(m,delta0,shelter)
prob1<-probcush(m,delta1,shelter)
maxpr<-max(prob0,prob1)
plot(1:m,prob0,ylim=c(0.0,1.1*maxpr),cex.main=0.9,las=1,
main="CUSH distributions, given delta-covariate=0, 1",cex=1.2,cex.lab=0.9,
xlab="",ylab="Prob(R|D=0) (circles) and Prob(R|D=1) (dots)",pch=1,lty=1,type="b");
lines(1:m,prob1,cex=1.2,pch=19,lty=2,type="b");
abline(h=0);
} else {
cat("No built-in plot method available for this variables specification","\n")
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/makeplot.R
|
#' @title Joint plot of estimated CUB models in the parameter space
#' @description Return a plot of estimated CUB models represented as points in the parameter space.
#' @aliases multicub
#' @usage multicub(listord,mvett,csiplot=FALSE,paiplot=FALSE,...)
#' @export multicub
#' @param listord A data matrix, data frame, or list of vectors of ordinal observations (for variables
#' with different number of observations)
#' @param mvett Vector of number of categories for ordinal variables in \code{listord} (optional: if missing,
#' the number of categories is retrieved from data: it is advisable to specify it in case some category has zero
#' frequency)
#' @param csiplot Logical: should \eqn{\xi} or \eqn{1-\xi} be the \eqn{y} coordinate
#' @param paiplot Logical: should \eqn{\pi} or \eqn{1-\pi} be the \eqn{x} coordinate
#' @param ... Additional arguments to be passed to \code{\link{plot}}, \code{\link{text}}, and \code{\link{GEM}}
#' @return Fit a CUB model to list elements, and then by default it returns a plot of the estimated
#' \eqn{(1-\pi, 1-\xi)} as points in the parameter space. Depending on \code{csiplot} and \code{paiplot}
#' and on desired output, \eqn{x} and \eqn{y} coordinates may be set to \eqn{\pi} and \eqn{\xi}, respectively.
#' @keywords device
#' @examples
#' data(univer)
#' listord<-univer[,8:12]
#' multicub(listord,colours=rep("red",5),cex=c(0.4,0.6,0.8,1,1.2),
#' pch=c(1,2,3,4,5),xlim=c(0,0.4),ylim=c(0.75,1),pos=c(1,3,3,3,3))
#' ###############################
#' m1<-5; m2<-7; m3<-9
#' pai<-0.7;csi<-0.6
#' n1<-1000; n2<-500; n3<-1500
#' ord1<-simcub(n1,m1,pai,csi)
#' ord2<-simcub(n2,m2,pai,csi)
#' ord3<-simcub(n3,m3,pai,csi)
#' listord<-list(ord1,ord2,ord3)
#' multicub(listord,labels=c("m=5","m=7","m=9"),pos=c(3,1,4))
multicub<-function(listord,mvett,csiplot=FALSE,paiplot=FALSE,...){
ellipsis.arg<-list(...)
if (is.data.frame(listord)==TRUE){
listord<- as.list(listord)
} else if (is.matrix(listord)==TRUE) {
mat<-as.data.frame(listord)
listord<- as.list(mat)
}
k<-length(listord)
if (missing(mvett)){
mvett<-c()
for (j in 1:k){
lev <- levels(factor(listord[[j]],ordered=TRUE));
mvett[j] <- length(lev)
}
}
xlim<-ellipsis.arg$xlim
if (is.null(xlim)){
xlim<-c(0,1)
}
ylim<-ellipsis.arg$ylim
if (is.null(ylim)){
ylim<-c(0,1)
}
pos<-ellipsis.arg$pos
if (is.null(pos)){
pos<-rep(3,length(listord))
} else if (length(pos)==1){
pos<-rep(pos,length(listord))
}
offset<-ellipsis.arg$offset
if (is.null(offset)){
offset<-0.5
}
font<-ellipsis.arg$font
if(is.null(font)){
font<-4
}
pch<-ellipsis.arg$pch
if (is.null(pch)){
pch<-rep(19,length(listord))
} else if (length(pch)==1){
pch<-rep(pch,length(listord))
}
cex<-ellipsis.arg$cex
if (is.null(cex)){
cex<-rep(0.5,length(listord))
} else if (length(cex)==1){
cex<-rep(cex,length(listord))
}
main<-ellipsis.arg$main
if(is.null(main)){
main<-"CUB models"
}
labels<-ellipsis.arg$labels
if(is.null(labels)){
labels<-as.character(1:length(listord))
}
colours<-ellipsis.arg$colours
if(is.null(colours)){
colours<-rep("black",length(listord))
} else if (length(colours)==1){
colours<-rep(colours,length(listord))
}
xlab<-ellipsis.arg$xlab
if(is.null(xlab)){
xlab<-expression(paste("Uncertainty ", (1-pi)))
if (paiplot==TRUE){
xlab<-expression(pi)
}
}
ylab<-ellipsis.arg$ylab
if(is.null(ylab)){
ylab<-expression(paste("Feeling ", (1-xi)))
if (csiplot==TRUE){
ylab<-expression(xi)
}
}
#listm<- mget('listm',ifnotfound=list(mlist))
#listm<-listm$listm
vettpai<-vettcsi<-rep(NA,k);
labelpoints<-c()
for(j in 1:k){
ord<-listord[[j]]
F0<-Formula(ord~0|0|0)
data<-as.data.frame(ord)
#stimacub<-CUB(F0,data=data,maxiter=300,toler=1e-4,m=listm[j])
stimacub <- GEM(F0,data=data,family="cub",maxiter=300,toler=1e-4,m=mvett[j])
param<-stimacub$estimates
vettpai[j]<-param[1]; vettcsi[j]<-param[2];
labelpoints[j]<-j
}
labels<-ellipsis.arg$labels
if(is.null(labels)){
labels<-labelpoints
}
plot(c(0,1),c(0,1),main=main,cex.main=1, font.lab=4,cex.lab=1,
pch=pch,las=1,type="n", xlim=xlim,ylim=ylim,xlab=xlab,ylab=ylab);
paival<-1-vettpai; csival<-1-vettcsi
if (csiplot==TRUE){
csival<-vettcsi
}
if (paiplot==TRUE){
paival<-vettpai
}
points(paival,csival,col=colours,pch=pch,cex=cex)
text(paival,csival,labels=labels,pos=pos,offset=offset,font=font,cex=cex,col=colours)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/multicub.R
|
#' @title Joint plot of estimated CUBE models in the parameter space
#' @description Return a plot of estimated CUBE models represented as points in the
#' parameter space, where the overdispersion is labeled.
#' @aliases multicube
#' @usage multicube(listord,mvett,csiplot=FALSE,paiplot=FALSE,...)
#' @export multicube
#' @param listord A data matrix, data frame, or list of vectors of ordinal observations (for variables
#' with different number of observations)
#' @param mvett Vector of number of categories for ordinal variables in \code{listord} (optional: if missing,
#' the number of categories is retrieved from data: it is advisable to specify it in case some category has zero
#' frequency)
#' @param csiplot Logical: should \eqn{\xi} or \eqn{1-\xi} be the \eqn{y} coordinate
#' @param paiplot Logical: should \eqn{\pi} or \eqn{1-\pi} be the \eqn{x} coordinate
#' @param ... Additional arguments to be passed to \code{\link{plot}}, \code{\link{text}}, and \code{\link{GEM}}
#' @keywords device
#' @return Fit a CUBE model to list elements, and then by default it returns a plot of the estimated
#' \eqn{(1-\pi, 1-\xi)} as points in the parameter space, labeled with the estimated overdispersion.
#' Depending on \code{csiplot} and \code{paiplot} and on desired output, \eqn{x} and \eqn{y}
#' coordinates may be set to \eqn{\pi} and \eqn{\xi}, respectively.
#' @examples
#' m1<-5; m2<-7; m3<-9
#' pai<-0.7;csi<-0.6;phi=0.1
#' n1<-1000; n2<-500; n3<-1500
#' ord1<-simcube(n1,m1,pai,csi,phi)
#' ord2<-simcube(n2,m2,pai,csi,phi)
#' ord3<-simcube(n3,m3,pai,csi,phi)
#' listord<-list(ord1,ord2,ord3)
#' multicube(listord,labels=c("m=5","m=7","m=9"),pos=c(3,1,4),expinform=TRUE)
multicube<-function(listord,mvett,csiplot=FALSE,paiplot=FALSE,...){
ellipsis.arg<-list(...)
if (is.data.frame(listord)==TRUE){
listord<- as.list(listord)
} else if (is.matrix(listord)==TRUE) {
mat<-as.data.frame(listord)
listord<- as.list(mat)
}
k<-length(listord)
if (missing(mvett)){
mvett<-c()
for (j in 1:k){
lev <- levels(factor(listord[[j]],ordered=TRUE));
mvett[j] <- length(lev)
}
}
xlim<-ellipsis.arg$xlim
if (is.null(xlim)){
xlim<-c(0,1)
}
ylim<-ellipsis.arg$ylim
if (is.null(ylim)){
ylim<-c(0,1)
}
pos<-ellipsis.arg$pos
if (is.null(pos)){
pos<-rep(3,length(listord))
} else if (length(pos)==1){
pos<-rep(pos,length(listord))
}
offset<-ellipsis.arg$offset
if (is.null(offset)){
offset<-0.5
}
font<-ellipsis.arg$font
if(is.null(font)){
font<-4
}
pch<-ellipsis.arg$pch
if (is.null(pch)){
pch<-rep(19,length(listord))
} else if (length(pch)==1){
pch<-rep(pch,length(listord))
}
cex<-ellipsis.arg$cex
if (is.null(cex)){
cex<-rep(0.5,length(listord))
} else if (length(cex)==1){
cex<-rep(cex,length(listord))
}
main<-ellipsis.arg$main
if(is.null(main)){
main<-"CUBE models"
}
labels<-ellipsis.arg$labels
if(is.null(labels)){
labels<-as.character(1:length(listord))
}
colours<-ellipsis.arg$colours
if(is.null(colours)){
colours<-rep("black",length(listord))
} else if (length(colours)==1){
colours<-rep(colours,length(listord))
}
xlab<-ellipsis.arg$xlab
if(is.null(xlab)){
xlab<-expression(paste("Uncertainty ", (1-pi)))
if (paiplot==TRUE){
xlab<-expression(pi)
}
}
ylab<-ellipsis.arg$ylab
if(is.null(ylab)){
ylab<-expression(paste("Feeling ", (1-xi)))
if (csiplot==TRUE){
ylab<-expression(xi)
}
}
vettpai<-vettcsi<-vettphi<-rep(NA,k);
labelpoints<-c()
for(j in 1:k){
ord<-listord[[j]]
m<-length(levels(factor(ord,ordered=TRUE)))
starting<-inibestcube(m,ord)
F0<-Formula(ord~0|0|0)
data<-as.data.frame(ord)
stimacube <- GEM(F0,data=data, family="cube",starting=starting,m=mvett[j])
#stimacube <- CUBE(F0,data=data, family="cube",starting=starting,m=listm[j])
param<-stimacube$estimates
vettpai[j]<-param[1]; vettcsi[j]<-param[2]; vettphi[j]<-round(param[3],digits=3)
labelpoints[j]=as.character(paste("phi=",vettphi[j]))
}
labels<-ellipsis.arg$labels
if(is.null(labels)){
labels<-labelpoints
}
plot(c(0,1),c(0,1),main=main,cex=cex,cex.main=1, font.lab=4,cex.lab=1,
pch=pch,las=1,type="n",
xlim=xlim,ylim=ylim,
xlab=xlab,ylab=ylab);
paival<-1-vettpai; csival<-1-vettcsi
if (csiplot==TRUE){
csival<-vettcsi
}
if (paiplot==TRUE){
paival<-vettpai
}
points(paival,csival,col=colours,pch=pch,cex=cex)
text(paival,csival,labels=labels,pos=pos,offset=offset,font=font,cex=cex,
col=colours)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/multicube.R
|
#' @title Generic function for coefficient names
#' @description Generic function for names of parameter estimates of object of class "GEM".
#' @aliases parnames.GEM
#' @param object An object of class "GEM"
#' @import methods
#' @keywords internal
#' @seealso \code{\link{summary}}
#' @examples
#' data(univer);attach(univer)
#' model<-GEM(Formula(officeho~0|0|0),family="cub",shelter=7)
#' model
parnames <- function(object) UseMethod("parnames", object)
parnames.GEM<-function(object){
listanomi<-c()
if (object$family=="CUB"){
listanomi<- parnames.CUB(object)
}
if (object$family=="CUBE"){
listanomi<- parnames.CUBE(object)
}
if (object$family=="IHG"){
listanomi<- parnames.IHG(object)
}
if (object$family=="CUSH"){
listanomi<- parnames.CUSH(object)
}
return(listanomi)
}
parnames.CUB<-function(object){
effe<-object$formula
# EFFE<-modello$Formula
data<-object$ellipsis$data
mf<-model.frame(effe,data=data,na.action=na.omit)
covpai<-model.matrix(effe,data=mf,rhs=1)
covcsi<-model.matrix(effe,data=mf,rhs=2)
covshe<-model.matrix(effe,data=mf,rhs=3)
if (ncol(covpai)==0){
Y<-NULL
} else {
if (NCOL(covpai)==2){
Y<-as.matrix(covpai[,-1])
colnames(Y)<-colnames(covpai)[2]
} else {
Y<-covpai[,-1]
}
}
if (ncol(covcsi)==0){
W<-NULL
} else {
if (NCOL(covcsi)==2){
W<-as.matrix(covcsi[,-1])
colnames(W)<-colnames(covcsi)[2]
} else {
W<-covcsi[,-1]
}
}
if (ncol(covshe)==0){
X<-NULL
} else {
if (NCOL(covshe)==2){
X<-as.matrix(covshe[,-1])
colnames(X)<-colnames(covshe)[2]
} else {
X<-covshe[,-1]
}
}
ellipsis<-object$ellipsis
listanomi<-c()
if (!is.null(ellipsis$shelter)){
if (is.null(X) & is.null(Y) & is.null(W)){
listanomi<-c("pai1","pai2","csi")
} else if (!is.null(X) & !is.null(Y) & !is.null(W)){
Y<-as.matrix(Y); W<-as.matrix(W); X<-as.matrix(X);
p<-NCOL(Y);
q<-NCOL(W);
s<-NCOL(X);
if (is.null(colnames(Y))){
nomiY<- paste("beta",0:p,sep="_")
} else {
nomiY<-c("constant",colnames(Y))
}
if (is.null(colnames(W))){
nomiW<- paste("gamma",0:q,sep="_")
} else {
nomiW<-c("constant",colnames(W))
}
if (is.null(colnames(X))){
nomiX<- paste("omega",0:s,sep="_")
} else {
nomiX<-c("constant",colnames(X))
}
listanomi<-c(nomiY,nomiW,nomiX);
}
} else {
if (is.null(Y) & is.null(W)){
listanomi<-c("pai","csi")
}
if (!is.null(Y) & is.null(W)){
betacoef<-c()
npar<-length(object$estimates)
if (!is.null(colnames(Y))){
betacoef<-c("constant",colnames(Y))
} else {
for (j in 1:(npar-1)){
betacoef[j]<-paste("beta",j-1,sep="_")
}
}
listanomi<-c(betacoef,"csi")
}
if (is.null(Y) & !is.null(W)){
gamacoef<-c()
npar<-length(object$estimates)
if (!is.null(colnames(W))){
gamacoef<-c("constant",colnames(W))
} else {
for (j in 1:(npar-1)){
gamacoef[j]<-paste("gamma",j-1,sep="_")
}
}
listanomi<-c("pai",gamacoef)
}
if (!is.null(Y) & !is.null(W)) {
betacoef<-gamacoef<-c()
Y<-as.matrix(Y); W<-as.matrix(W)
ny<-NCOL(Y); nw<-NCOL(W);
if (is.null(colnames(Y))){
for (j in 1:(ny+1)){
betacoef[j]<-paste("beta",j-1,sep="_")
}
} else {
betacoef<-c("constant",colnames(Y))
}
if (is.null(colnames(W))){
for (j in 1:(nw+1)){
gamacoef[j]<-paste("gamma",j-1,sep="_")
}
} else {
gamacoef<-c("constant",colnames(W))
}
listanomi<-c(betacoef,gamacoef)
}
}
return(listanomi)
}
#####################################################
parnames.CUBE<-function(object){
ellipsis<-object$ellipsis
effe<-object$formula
# EFFE<-modello$Formula
data<-object$ellipsis$data
mf<-model.frame(effe,data=data,na.action=na.omit)
covpai<-model.matrix(effe,data=mf,rhs=1)
covcsi<-model.matrix(effe,data=mf,rhs=2)
covphi<-model.matrix(effe,data=mf,rhs=3)
if (ncol(covpai)==0){
Y<-NULL
} else {
if (NCOL(covpai)==2){
Y<-as.matrix(covpai[,-1])
colnames(Y)<-colnames(covpai)[2]
} else {
Y<-covpai[,-1]
}
}
if (ncol(covcsi)==0){
W<-NULL
} else {
if (NCOL(covcsi)==2){
W<-as.matrix(covcsi[,-1])
colnames(W)<-colnames(covcsi)[2]
} else {
W<-covcsi[,-1]
}
}
if (ncol(covphi)==0){
Z<-NULL
} else {
if (NCOL(covphi)==2){
Z<-as.matrix(covphi[,-1])
colnames(Z)<-colnames(covphi)[2]
} else {
Z<-covphi[,-1]
}
}
listanomi<-c()
if (is.null(Y) & is.null(W) & is.null(Z)){
listanomi<-rbind("pai","csi","phi")
} else if (is.null(Y) & is.null(Z) & !is.null(W)){
W<-as.matrix(W)
if (is.null(colnames(W))){
gamacoef<- paste("gamma",0:NCOL(W),sep="_")
} else {
gamacoef<-c("constant",colnames(W))
}
listanomi<-c("pai",gamacoef,"phi")
} else if (!is.null(Y) & !is.null(Z) & !is.null(W)){
W<-as.matrix(W); Y<-as.matrix(Y); Z<-as.matrix(Z);
if (is.null(colnames(W))){
gamacoef<- paste("gamma",0:NCOL(W),sep="_")
} else {
gamacoef<-c("constant",colnames(W))
}
if (is.null(colnames(Y))){
betacoef<- paste("beta",0:NCOL(Y),sep="_")
} else {
betacoef<-c("constant",colnames(Y))
}
if (is.null(colnames(Z))){
alfacoef<- paste("alpha",0:NCOL(Z),sep="_")
} else {
alfacoef<-c("constant",colnames(Z))
}
listanomi<-c(betacoef, gamacoef, alfacoef)
} else {
cat("CUBE models not available for this variables specification")
listanomi<-c()
}
return(listanomi)
}
#####################################################
parnames.IHG<-function(object){
ellipsis<-object$ellipsis
# U<-ellipsis$U
effe<-object$formula
data<-object$ellipsis$data
mf<-model.frame(effe,data=data,na.action=na.omit)
covtheta<-model.matrix(effe,data=mf,rhs=1)
if (ncol(covtheta)==0){
U<-NULL
} else {
if (NCOL(covtheta)==2){
U<-as.matrix(covtheta[,-1])
colnames(U)<-colnames(covtheta)[2]
} else {
U<-covtheta[,-1]
}
}
listanomi<-c()
if (is.null(U)){
listanomi<-"theta"
} else {
U<-as.matrix(U)
if (is.null(colnames(U))){
listanomi<-paste("nu",0:NCOL(U),sep="_")
} else {
listanomi<-c("constant",colnames(U))
}
}
return(listanomi)
}
#####################################################
parnames.CUSH<-function(object){
ellipsis<-object$ellipsis
# X<-ellipsis$X
effe<-object$formula
# EFFE<-mod$Formula
data<-object$ellipsis$data
mf<-model.frame(effe,data=data,na.action=na.omit)
covshe<-model.matrix(effe,data=mf,rhs=1)
if (ncol(covshe)==0){
X<-NULL
} else {
if (NCOL(covshe)==2){
X<-as.matrix(covshe[,-1])
colnames(X)<-colnames(covshe)[2]
} else {
X<-covshe[,-1]
}
}
listanomi<-c()
if (is.null(X)){
listanomi<-"delta"
} else {
X<-as.matrix(X)
if (is.null(colnames(X))){
listanomi<-paste("omega",0:NCOL(X),sep="_")
} else {
listanomi<-c("constant",colnames(X))
}
}
return(listanomi)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/parnames.R
|
#' @title Plot of the log-likelihood function of the IHG distribution
#' @aliases plotloglikihg
#' @description Plot the log-likelihood function of an IHG model fitted to a given absolute frequency distribution,
#' over the whole support of the preference parameter. It returns also the ML estimate.
#' @usage plotloglikihg(m,freq)
#' @export plotloglikihg
#' @param m Number of ordinal categories
#' @param freq Vector of the absolute frequency distribution
#' @seealso \code{\link{loglikIHG}}
#' @examples
#' m<-7
#' freq<-c(828,275,202,178,143,110,101)
#' max<-plotloglikihg(m,freq)
plotloglikihg <-
function(m,freq){
np<-1000
ordinate<-rep(NA,np)
ini<-1; fin<-np;
thetavec<-(1:np)/np
for(j in 1:np){
ordinate[j]<-loglikihg(m,freq,thetavec[j])
}
plot(thetavec[ini:fin],ordinate[ini:fin],type="l",lwd=3,xlab=expression(theta),ylab="Log-likelihood function",
cex.main=0.9,main="Log-likelihood function for the Inverse HyperGeometric distribution")
which.max(ordinate)/np ### MLE of theta
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/plotloglikihg.R
|
#' @title S3 method: print for class "GEM"
#' @description S3 method print for objects of class \code{\link{GEM}}.
#' @aliases print.GEM
#' @method print GEM
#' @param x An object of class \code{\link{GEM}}
#' @param ... Other arguments
#' @export
#' @return Brief summary results of the fitting procedure, including parameter estimates, their standard errors and
#' the executed call.
#' @import methods
#' @rdname print.GEM
#' @keywords package
print.GEM<-function(x,...){
arguments<-list(...)
digits<-arguments$digits
if (is.null(digits)){
digits<-options()$digits
}
if(!is.null(cl <- x$call)){
cat("Call:\n")
dput(cl, control = NULL)
}
sterr<-as.numeric(round(sqrt(diag(vcov(x))),digits=digits))
mat<-cbind(round(x$estimates,digits=digits),sterr)
rownames(mat)<-parnames(x)
colnames(mat)<-c("Estimates","Standard Errors")
object<-x$object
family<-object$family
stime<-object$estimates
cat("","\n")
print(mat)
# cat("Coefficients:","\n")
# print(coef(x,digits=digits))
cat("","\n")
cat("Maximized Log-Likelihood:",logLik(x,digits=digits),"\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/print.R
|
#' @title Probability distribution of a shifted Binomial random variable
#' @description Return the shifted Binomial probability distribution.
#' @aliases probbit
#' @usage probbit(m,csi)
#' @param m Number of ordinal categories
#' @param csi Feeling parameter
#' @import stats
#' @export probbit
#' @return The vector of the probability distribution of a shifted Binomial model.
#' @keywords distribution
#' @seealso \code{\link{bitcsi}}, \code{\link{probcub00}}
#' @examples
#' m<-7
#' csi<-0.7
#' pr<-probbit(m,csi)
#' plot(1:m,pr,type="h",main="Shifted Binomial probability distribution",xlab="Categories")
#' points(1:m,pr,pch=19)
probbit <-
function(m,csi){dbinom(0:(m-1),m-1,1-csi)}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probbit.R
|
#' @title Probability distribution of a CUB model without covariates
#' @description Compute the probability distribution of a CUB model without covariates.
#' @aliases probcub00
#' @usage probcub00(m,pai,csi)
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @export probcub00
#' @return The vector of the probability distribution of a CUB model.
#' @keywords distribution
#' @seealso \code{\link{bitcsi}}, \code{\link{probcub0q}}, \code{\link{probcubp0}}, \code{\link{probcubpq}}
#' @references
#' Piccolo D. (2003). On the moments of a mixture of uniform and shifted binomial random variables.
#' \emph{Quaderni di Statistica}, \bold{5}, 85--104\cr
#' @examples
#' m<-9
#' pai<-0.3
#' csi<-0.8
#' pr<-probcub00(m,pai,csi)
#' plot(1:m,pr,type="h",main="CUB probability distribution",xlab="Ordinal categories")
#' points(1:m,pr,pch=19)
probcub00 <-function(m,pai,csi){
pai*(probbit(m,csi)-1/m)+1/m
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcub00.R
|
#' @title Probability distribution of a CUB model with covariates for the feeling component
#' @aliases probcub0q
#' @description Compute the probability distribution of a CUB model with covariates
#' for the feeling component.
#' @export probcub0q
#' @usage probcub0q(m,ordinal,W,pai,gama)
#' @keywords distribution
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param W Matrix of covariates for explaining the feeling component
#' NCOL(Y)+1 to include an intercept term in the model (first entry)
#' @param pai Uncertainty parameter
#' @param gama Vector of parameters for the feeling component, whose length equals
#' NCOL(W)+1 to include an intercept term in the model (first entry)
#' @return A vector of the same length as \code{ordinal}, whose i-th component is the
#' probability of the i-th observation according to a CUB distribution with the corresponding values
#' of the covariates for the feeling component and coefficients specified in \code{gama}.
#' @seealso \code{\link{bitgama}}, \code{\link{probcub00}}, \code{\link{probcubp0}},
#' \code{\link{probcubpq}}
#' @references
#' Piccolo D. (2006). Observed Information Matrix for MUB Models,
#' \emph{Quaderni di Statistica}, \bold{8}, 33--78 \cr
#' Piccolo D. and D'Elia A. (2008). A new approach for modelling consumers' preferences, \emph{Food Quality and Preference},
#' \bold{18}, 247--259 \cr
#' Iannario M. and Piccolo D. (2012). CUB models: Statistical methods and empirical evidence, in:
#' Kenett R. S. and Salini S. (eds.), \emph{Modern Analysis of Customer Surveys: with applications using R},
#' J. Wiley and Sons, Chichester, 231--258
#' @examples
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Physician))
#' nacov<-which(is.na(relgoods$Gender))
#' na<-union(naord,nacov)
#' ordinal<-relgoods$Physician[-na]
#' W<-relgoods$Gender[-na]
#' pai<-0.44; gama<-c(-0.91,-0.7)
#' pr<-probcub0q(m,ordinal,W,pai,gama)
probcub0q <-
function(m,ordinal,W,pai,gama){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
as.numeric(pai*(bitgama(m,ordinal,W,gama)-1/m)+1/m)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcub0q.R
|
#' @title Probability distribution of a CUBE model without covariates
#' @aliases probcube
#' @description Compute the probability distribution of a CUBE model without covariates.
#' @usage probcube(m,pai,csi,phi)
#' @export probcube
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @param phi Overdispersion parameter
#' @return The vector of the probability distribution of a CUBE model without covariates.
#' @seealso \code{\link{betar}}, \code{\link{betabinomial}}
#' @references
#' Iannario, M. (2014). Modelling Uncertainty and Overdispersion in Ordinal Data,
#' \emph{Communications in Statistics - Theory and Methods}, \bold{43}, 771--786
#' @keywords distribution
#' @examples
#' m<-9
#' pai<-0.3
#' csi<-0.8
#' phi<-0.1
#' pr<-probcube(m,pai,csi,phi)
#' plot(1:m,pr,type="h", main="CUBE probability distribution",xlab="Ordinal categories")
#' points(1:m,pr,pch=19)
probcube <-
function(m,pai,csi,phi){
pai*(betar(m,csi,phi)-1/m)+1/m
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcube.R
|
#' @title Probability distribution of a CUB model with covariates for the uncertainty component
#' @aliases probcubp0
#' @description Compute the probability distribution of a CUB model with covariates for the
#' uncertainty component.
#' @export probcubp0
#' @usage probcubp0(m,ordinal,Y,bet,csi)
#' @keywords distribution
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of covariates for explaining the uncertainty component
#' @param bet Vector of parameters for the uncertainty component, whose length equals
#' NCOL(Y) + 1 to include an intercept term in the model (first entry)
#' @param csi Feeling parameter
#' @return A vector of the same length as \code{ordinal}, whose i-th component is the probability of the i-th
#' observation according to a CUB model with the corresponding values of the covariates for the
#' uncertainty component and coefficients for the covariates specified in \code{bet}.
#' @references
#' Piccolo D. (2006). Observed Information Matrix for MUB Models,
#' \emph{Quaderni di Statistica}, \bold{8}, 33--78 \cr
#' Piccolo D. and D'Elia A. (2008). A new approach for modelling consumers' preferences, \emph{Food Quality and Preference},
#' \bold{18}, 247--259 \cr
#' Iannario M. and Piccolo D. (2012). CUB models: Statistical methods and empirical evidence, in:
#' Kenett R. S. and Salini S. (eds.), \emph{Modern Analysis of Customer Surveys: with applications using R},
#' J. Wiley and Sons, Chichester, 231--258
#' @seealso \code{\link{bitgama}}, \code{\link{probcub00}}, \code{\link{probcubpq}}, \code{\link{probcub0q}}
#' @examples
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Physician))
#' nacov<-which(is.na(relgoods$Gender))
#' na<-union(naord,nacov)
#' ordinal<-relgoods$Physician[-na]
#' Y<-relgoods$Gender[-na]
#' bet<-c(-0.81,0.93); csi<-0.20
#' probi<-probcubp0(m,ordinal,Y,bet,csi)
probcubp0 <-
function(m,ordinal,Y,bet,csi){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
Y<-as.matrix(Y)
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
as.numeric(logis(Y,bet)*(bitcsi(m,ordinal,csi)-1/m)+1/m)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcubp0.R
|
#' @title Probability distribution of a CUB model with covariates for both feeling and uncertainty
#' @aliases probcubpq
#' @description Compute the probability distribution of a CUB model with covariates for both the feeling
#' and the uncertainty components.
#' @export probcubpq
#' @usage probcubpq(m,ordinal,Y,W,bet,gama)
#' @keywords distribution
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of covariates for explaining the uncertainty component
#' @param W Matrix of covariates for explaining the feeling component
#' @param bet Vector of parameters for the uncertainty component, whose length equals
#' NCOL(Y) + 1 to include an intercept term in the model (first entry)
#' @param gama Vector of parameters for the feeling component, whose length equals
#' NCOL(W)+1 to include an intercept term in the model (first entry)
#' @return A vector of the same length as \code{ordinal}, whose i-th component is the probability of the
#' i-th rating according to a CUB distribution with given covariates for both uncertainty and feeling,
#' and specified coefficients vectors \code{bet} and \code{gama}, respectively.
#' @seealso \code{\link{bitgama}}, \code{\link{probcub00}}, \code{\link{probcubp0}}, \code{\link{probcub0q}}
#' @references
#' Piccolo D. (2006). Observed Information Matrix for MUB Models,
#' \emph{Quaderni di Statistica}, \bold{8}, 33--78 \cr
#' Piccolo D. and D'Elia A. (2008). A new approach for modelling consumers' preferences, \emph{Food Quality and Preference},
#' \bold{18}, 247--259 \cr
#' Iannario M. and Piccolo D. (2012). CUB models: Statistical methods and empirical evidence, in:
#' Kenett R. S. and Salini S. (eds.), \emph{Modern Analysis of Customer Surveys: with applications using R},
#' J. Wiley and Sons, Chichester, 231--258
#' @examples
#' data(relgoods)
#' m<-10
#' naord<-which(is.na(relgoods$Physician))
#' nacov<-which(is.na(relgoods$Gender))
#' na<-union(naord,nacov)
#' ordinal<-relgoods$Physician[-na]
#' W<-Y<-relgoods$Gender[-na]
#' gama<-c(-0.91,-0.7); bet<-c(-0.81,0.93)
#' probi<-probcubpq(m,ordinal,Y,W,bet,gama)
probcubpq <-
function(m,ordinal,Y,W,bet,gama){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
Y<-as.matrix(Y); W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
logis(Y,bet)*(bitgama(m,ordinal,W,gama)-1/m)+1/m
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcubpq.R
|
#' @title probcubshe1
#' @aliases probcubshe1
#' @description Probability distribution of an extended CUB model with a shelter effect.
#' @usage probcubshe1(m,pai1,pai2,csi,shelter)
#' @export probcubshe1
#' @keywords distribution
#' @param m Number of ordinal categories
#' @param pai1 Mixing coefficient for the shifted Binomial component of the mixture distribution
#' @param pai2 Mixing coefficient for the discrete Uniform component of the mixture distribution
#' @param csi Feeling parameter
#' @param shelter Category corresponding to the shelter choice
#' @return The vector of the probability distribution of an extended CUB model with a shelter effect
#' at the shelter category
#' @details An extended CUB model is a mixture of three components: a shifted Binomial distribution
#' with probability of success \eqn{\xi}, a discrete uniform distribution with support \eqn{\{1,...,m\}},
#' and a degenerate distribution with unit mass at the shelter category (\code{shelter}).
#' @references
#' Iannario M. (2012). Modelling \emph{shelter} choices in a class of mixture models for ordinal responses,
#' \emph{Statistical Methods and Applications}, \bold{21}, 1--22 \cr
#' @seealso \code{\link{probcubshe2}}, \code{\link{probcubshe3}}
#' @examples
#' m<-8
#' pai1<-0.5
#' pai2<-0.3
#' csi<-0.4
#' shelter<-6
#' pr<-probcubshe1(m,pai1,pai2,csi,shelter)
#' plot(1:m,pr,type="h",main="Extended CUB probability distribution with shelter effect",
#' xlab="Ordinal categories")
#' points(1:m,pr,pch=19)
probcubshe1 <-
function(m,pai1,pai2,csi,shelter)
{pai1*probbit(m,csi)+pai2*(1/m)+(1-pai1-pai2)*ifelse(seq(1,m)==shelter,1,0)}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcubshe1.R
|
#' @title probcubshe2
#' @aliases probcubshe2
#' @description Probability distribution of a CUB model with explicit shelter effect
#' @usage probcubshe2(m,pai,csi,delta,shelter)
#' @export probcubshe2
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @param delta Shelter parameter
#' @param shelter Category corresponding to the shelter choice
#' @return The vector of the probability distribution of a CUB model with explicit shelter effect.
#' @details A CUB model with explicit shelter effect is a mixture of two components:
#' a CUB distribution with uncertainty parameter \eqn{\pi} and feeling parameter \eqn{\xi},
#' and a degenerate distribution with unit mass at the shelter category (\code{shelter})
#' with mixing coefficient specified by \eqn{\delta}.
#' @references
#' Iannario M. (2012). Modelling \emph{shelter} choices in a class of mixture models for ordinal responses,
#' \emph{Statistical Methods and Applications}, \bold{21}, 1--22 \cr
#' @seealso \code{\link{probcubshe1}}, \code{\link{probcubshe3}}
#' @keywords distribution
#' @examples
#' m<-8
#' pai1<-0.5
#' pai2<-0.3
#' csi<-0.4
#' shelter<-6
#' delta<-1-pai1-pai2
#' pai<-pai1/(1-delta)
#' pr2<-probcubshe2(m,pai,csi,delta,shelter)
#' plot(1:m,pr2,type="h", main="CUB probability distribution with
#' explicit shelter effect",xlab="Ordinal categories")
#' points(1:m,pr2,pch=19)
probcubshe2 <-
function(m,pai,csi,delta,shelter)
{delta*ifelse(seq(1,m)==shelter,1,0)+(1-delta)*(pai*probbit(m,csi)+(1-pai)*(1/m))}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcubshe2.R
|
#' @title probcubshe3
#' @aliases probcubshe3
#' @description Probability distribution of a CUB model with explicit shelter effect:
#' satisficing interpretation
#' @usage probcubshe3(m,lambda,eta,csi,shelter)
#' @export probcubshe3
#' @keywords distribution
#' @param m Number of ordinal categories
#' @param lambda Mixing coefficient for the shifted Binomial component
#' @param eta Mixing coefficient for the mixture of the uncertainty component and the
#' shelter effect
#' @param csi Feeling parameter
#' @param shelter Category corresponding to the shelter choice
#' @return The vector of the probability distribution of a CUB model with shelter effect.
#' @details The "satisficing interpretation" provides a parametrization for CUB models with explicit
#' shelter effect as a mixture of two components: a shifted Binomial distribution with feeling parameter
#' \eqn{\xi} (meditated choice), and a mixture of a degenerate distribution with unit mass at the shelter
#' category (\code{shelter}) and a discrete uniform distribution over \eqn{m} categories, with mixing
#' coefficient specified by \eqn{\eta} (lazy selection of a category).
#' @references
#' Iannario M. (2012). Modelling \emph{shelter} choices in a class of mixture models for ordinal responses,
#' \emph{Statistical Methods and Applications}, \bold{21}, 1--22 \cr
#' @seealso \code{\link{probcubshe1}}, \code{\link{probcubshe2}}
#' @examples
#' m<-8
#' pai1<-0.5
#' pai2<-0.3
#' csi<-0.4
#' shelter<-6
#' lambda<-pai1
#' eta<-1-pai2/(1-pai1)
#' pr3<-probcubshe3(m,lambda,eta,csi,shelter)
#' plot(1:m,pr3,type="h",main="CUB probability distribution with explicit
#' shelter effect",xlab="Ordinal categories")
#' points(1:m,pr3,pch=19)
probcubshe3 <-
function(m,lambda,eta,csi,shelter){
lambda*probbit(m,csi)+(1-lambda)*((1-eta)/m + eta*ifelse(seq(1,m)==shelter,1,0))
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcubshe3.R
|
#' @title Probability distribution of a CUSH model
#' @aliases probcush
#' @description Compute the probability distribution of a CUSH model without covariates, that is a mixture of a
#' degenerate random variable with mass at the shelter category and the Uniform distribution.
#' @keywords distribution
#' @export probcush
#' @usage probcush(m,delta,shelter)
#' @param m Number of ordinal categories
#' @param delta Shelter parameter
#' @param shelter Category corresponding to the shelter choice
#' @return The vector of the probability distribution of a CUSH model without covariates.
#' @references
#' Capecchi S. and Piccolo D. (2017). Dealing with heterogeneity in ordinal responses,
#' \emph{Quality and Quantity}, \bold{51}(5), 2375--2393 \cr
#' Capecchi S. and Iannario M. (2016). Gini heterogeneity index for detecting uncertainty in ordinal data surveys,
#' \emph{Metron}, \bold{74}(2), 223--232
#' @examples
#' m<-10
#' shelter<-1
#' delta<-0.4
#' pr<-probcush(m,delta,shelter)
#' plot(1:m,pr,type="h",xlab="Number of categories")
#' points(1:m,pr,pch=19)
probcush <-
function(m,delta,shelter){
delta*(ifelse(seq(1,m)==shelter,1,0) - 1/m) + 1/m
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probcush.R
|
#' @title Probability distribution of a GeCUB model
#' @aliases probgecub
#' @description Compute the probability distribution of a GeCUB model, that is a CUB model with
#' shelter effect with covariates specified for all component.
#' @export probgecub
#' @usage probgecub(ordinal,Y,W,X,bet,gama,omega,shelter)
#' @keywords distribution
#' @param ordinal Vector of ordinal responses
#' @param Y Matrix of covariates for explaining the uncertainty component
#' @param W Matrix of covariates for explaining the feeling component
#' @param X Matrix of covariates for explaining the shelter effect
#' @param bet Vector of parameters for the uncertainty component, whose length equals
#' NCOL(Y)+1 to include an intercept term in the model (first entry)
#' @param gama Vector of parameters for the feeling component, whose length equals
#' NCOL(W)+1 to include an intercept term in the model (first entry)
#' @param omega Vector of parameters for the shelter effect, whose length equals
#' NCOL(X)+1 to include an intercept term in the model (first entry)
#' @param shelter Category corresponding to the shelter choice
#' @return A vector of the same length as \code{ordinal}, whose i-th component is the
#' probability of the i-th observation according to a GeCUB model with the corresponding values
#' of the covariates for all the components and coefficients specified in \code{bet}, \code{gama}, \code{omega}.
#' @references
#' Iannario M. and Piccolo D. (2016b). A generalized framework for modelling ordinal data.
#' \emph{Statistical Methods and Applications}, \bold{25}, 163--189.\cr
probgecub<-function(ordinal,Y,W,X,bet,gama,omega,shelter){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
X<-as.matrix(X); Y<-as.matrix(Y); W<-as.matrix(W)
if (ncol(W)==1){
W<-as.numeric(W)
}
if (ncol(Y)==1){
Y<-as.numeric(Y)
}
if (ncol(X)==1){
X<-as.numeric(X)
}
alpha1<-logis(X,omega);
alpha2<-(1-alpha1)*(logis(Y,bet));
pshe<-ifelse(as.numeric(ordinal)==shelter,1,0)
ord<-factor(ordinal,ordered=TRUE)
m<-length(levels(ord))
vettore<-alpha1*pshe + alpha2*(bitgama(m,ordinal,W,gama)) + (1-alpha1-alpha2)*(1/m);
return(vettore)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probgecub.R
|
#' @title Probability distribution of an IHG model
#' @aliases probihg
#' @description Compute the probability distribution of an IHG model (Inverse Hypergeometric) without covariates.
#' @keywords distribution
#' @export probihg
#' @usage probihg(m,theta)
#' @param m Number of ordinal categories
#' @param theta Preference parameter
#' @return The vector of the probability distribution of an IHG model.
#' @references
#' D'Elia A. (2003). Modelling ranks using the inverse hypergeometric distribution,
#' \emph{Statistical Modelling: an International Journal}, \bold{3}, 65--78
#' @examples
#' m<-10
#' theta<-0.30
#' pr<-probihg(m,theta)
#' plot(1:m,pr,type="h",xlab="Ordinal categories")
#' points(1:m,pr,pch=19)
probihg <-
function(m,theta){
pr<-rep(NA,m)
pr[1]<-theta
for(j in 1:(m-1)){
pr[j+1]<-pr[j]*(1-theta)*(m-j)/(m-j-1+j*theta)
}
return(pr)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probihg.R
|
#' @title Probability distribution of an IHG model with covariates
#' @aliases probihgcovn
#' @description Given a vector of \eqn{n} ratings over \eqn{m} categories, it returns a vector
#' of length \eqn{n} whose i-th element is the probability of observing the i-th rating for the
#' corresponding IHG model with parameter \eqn{\theta_i}, obtained via logistic link with covariates
#' and coefficients.
#' @keywords distribution
#' @export probihgcovn
#' @usage probihgcovn(m,ordinal,U,nu)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param U Matrix of selected covariates for explaining the preference parameter
#' @param nu Vector of coefficients for covariates, whose length equals NCOL(U)+1 to include
#' an intercept term in the model (first entry)
#' @details The matrix \eqn{U} is expanded with a vector with entries equal to 1 in the first column to include
#' an intercept term in the model.
#' @seealso \code{\link{probihg}}
#' @examples
#' n<-100
#' m<-7
#' theta<-0.30
#' ordinal<-simihg(n,m,theta)
#' U<-sample(c(0,1),n,replace=TRUE)
#' nu<-c(0.12,-0.5)
#' pr<-probihgcovn(m,ordinal,U,nu)
probihgcovn <-
function(m,ordinal,U,nu){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
n<-length(ordinal)
vett<-rep(NA,n)
U<-as.matrix(U)
if (ncol(U)==1){
U<-as.numeric(U)
}
thetavett<-logis(U,nu)
for (i in 1:n){
prob<-probihg(m,thetavett[i])
vett[i]<-prob[ordinal[i]]
}
return(vett)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/probihgcovn.R
|
#' @title Relational goods and Leisure time dataset
#' @description Dataset consists of the results of a survey aimed at measuring the evaluation
#' of people living in the metropolitan area of Naples, Italy, with respect to of relational goods and
#' leisure time collected in December 2014. Every participant was asked
#' to assess on a 10 point ordinal scale his/her personal score for several relational goods
#' (for instance, time dedicated to friends and family) and to leisure time.
#' In addition, the survey asked respondents to self-evaluate their level of happiness by marking
#' a sign along a horizontal line of 110 millimeters according to their feeling, with the left-most
#' extremity standing for "extremely unhappy", and the right-most extremity corresponding to
#' the status "extremely happy".
#' @aliases relgoods
#' @usage data(relgoods)
#' @format The description of subjects' covariates is the following:
#' \describe{
#' \item{\code{ID}}{An identification number}
#' \item{\code{Gender}}{A factor with levels: 0 = man, 1 = woman}
#' \item{\code{BirthMonth}}{A variable indicating the month of birth of the respondent}
#' \item{\code{BirthYear}}{A variable indicating the year of birth of the respondent}
#' \item{\code{Family}}{A factor variable indicating the number of members of the family}
#' \item{\code{Year.12}}{A factor with levels: 1 = if there is any child aged less than 12 in the family,
#' 0 = otherwise}
#' \item{\code{EducationDegree}}{A factor with levels: 1 = compulsory school, 2 = high school diploma,
#' 3 = Graduated-Bachelor degree, 4 = Graduated-Master degree, 5 = Post graduated}
#' \item{\code{MaritalStatus}}{A factor with levels: 1 = Unmarried, 2 = Married/Cohabitee,
#' 3 = Separated/Divorced, 4 = Widower}
#' \item{\code{Residence}}{A factor with levels: 1 = City of Naples, 2 = District of Naples,
#' 3 = Others Campania, 4 = Others Italia, 5 = Foreign countries}
#' \item{\code{Glasses}}{A factor with levels: 1 = wearing glasses or contact lenses, 0 = otherwise}
#' \item{\code{RightHand}}{A factor with levels: 1 = right-handed, 0 = left-handed}
#' \item{\code{Smoking}}{A factor with levels: 1 = smoker, 0 = not smoker}
#' \item{\code{WalkAlone}}{A factor with levels: 1 = usually walking alone, 0 = usually walking in company}
#' \item{\code{job}}{A factor with levels: 1 = Not working, 2 = Retired, 3 = occasionally,
#' 4 = fixed-term job, 5 = permanent job}
#' \item{\code{PlaySport}}{A factor with levels: 1 = Not playing any sport, 2 = Yes, individual sport,
#' 3 = Yes, team sport}
#' \item{\code{Pets}}{A factor with levels: 1 = owning a pet, 0 = not owning any pet}
#'}
#' 1) Respondents were asked to evaluate the following items on a 10 point Likert scale,
#' ranging from 1 = "never, at all" to 10 = "always, a lot":
#' \describe{
#' \item{\code{WalkOut}}{How often the respondent goes out for a walk}
#' \item{\code{Parents}}{How often respondent talks at least to one of his/her parents}
#' \item{\code{MeetRelatives}}{How often respondent meets his/her relatives}
#' \item{\code{Association}}{Frequency of involvement in volunteering or different kinds of
#' associations/parties, etc}
#' \item{\code{RelFriends}}{Quality of respondent's relationships with friends}
#' \item{\code{RelNeighbours}}{Quality of the relationships with neighbors}
#' \item{\code{NeedHelp}}{Easiness in asking help whenever in need}
#' \item{\code{Environment}}{Level of comfort with the surrounding environment}
#' \item{\code{Safety}}{Level of safety in the streets}
#' \item{\code{EndofMonth}}{Family making ends meet}
#' \item{\code{MeetFriend}}{Number of times the respondent met his/her friends during the month
#' preceding the interview}
#' \item{\code{Physician}}{Importance of the kindness/simpathy in the selection of respondent's physician}
#' }
#' \describe{
#' \item{\code{Happiness}}{Each respondent was asked to mark a sign on a 110mm horizontal line
#' according to his/her feeling of happiness (left endpoint corresponding to completely unhappy,
#' right-most endpoint corresponding to extremely happy}
#' }
#' 2) The same respondents were asked to score the activities for leisure time listed below, according
#' to their involvement/degree of amusement, on a 10 point Likert scale
#' ranging from 1 = "At all, nothing, never" to 10 = "Totally, extremely important, always":
#' \describe{
#' \item{\code{Videogames}}{}
#' \item{\code{Reading}}{}
#' \item{\code{Cinema}}{}
#' \item{\code{Drawing}}{}
#' \item{\code{Shopping}}{}
#' \item{\code{Writing}}{}
#' \item{\code{Bicycle}}{}
#' \item{\code{Tv}}{}
#' \item{\code{StayWFriend}}{Spending time with friends}{}
#' \item{\code{Groups}}{Taking part to associations, meetings, etc.}{}
#' \item{\code{Walking}}{}
#' \item{\code{HandWork}}{Hobby, gardening, sewing, etc. }
#' \item{\code{Internet}}{}
#' \item{\code{Sport}}{}
#' \item{\code{SocialNetwork}}{}
#' \item{\code{Gym}}{}
#' \item{\code{Quiz}}{Crosswords, sudoku, etc.}
#' \item{\code{MusicInstr}}{Playing a musical instrument}
#' \item{\code{GoAroundCar}}{ Hanging out by car}
#' \item{\code{Dog}}{Walking out the dog}
#' \item{\code{GoOutEat}}{Go to restaurants/pubs}}
#' @keywords datasets
#' @details
#' Period of data collection: December 2014 \cr
#' Mode of collection: questionnaire \cr
#' Number of observations: 2459 \cr
#' Number of subjects' covariates: 16 \cr
#' Number of analyzed items: 34 \cr
#' Warning: with a limited number of missing values
"relgoods"
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/relgoods.R
|
#' @title Simulation routine for CUB models
#' @aliases simcub
#' @description Generate \eqn{n} pseudo-random observations following the given CUB distribution.
#' @keywords distribution
#' @usage simcub(n,m,pai,csi)
#' @export simcub
#' @import stats
#' @param n Number of simulated observations
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @seealso \code{\link{probcub00}}
#' @examples
#' n<-300
#' m<-9
#' pai<-0.4
#' csi<-0.7
#' simulation<-simcub(n,m,pai,csi)
#' plot(table(simulation),xlab="Ordinal categories",ylab="Frequencies")
simcub <-
function(n,m,pai,csi){
dico<-runif(n)<pai;
vett<-dico*(1+rbinom(n,m-1,1-csi))+(1-dico)*sample(m,n,replace=TRUE)
return(vett)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/simcub.R
|
#' @title Simulation routine for CUBE models
#' @aliases simcube
#' @description Generate \eqn{n} pseudo-random observations following the given CUBE
#' distribution.
#' @keywords distribution
#' @usage simcube(n,m,pai,csi,phi)
#' @export simcube
#' @param n Number of simulated observations
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @param phi Overdispersion parameter
#' @seealso \code{\link{probcube}}
#' @examples
#' n<-300
#' m<-9
#' pai<-0.7
#' csi<-0.4
#' phi<-0.1
#' simulation<-simcube(n,m,pai,csi,phi)
#' plot(table(simulation),xlab="Ordinal categories",ylab="Frequencies")
simcube <-
function(n,m,pai,csi,phi){
prob<-probcube(m,pai,csi,phi)
ord<-sample(1:m,n,prob,replace=T)
return(ord)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/simcube.R
|
#' @title Simulation routine for CUB models with shelter effect
#' @aliases simcubshe
#' @description Generate \eqn{n} pseudo-random observations following the given CUB distribution
#' with shelter effect.
#' @keywords distribution
#' @usage simcubshe(n,m,pai,csi,delta,shelter)
#' @export simcubshe
#' @import stats
#' @param n Number of simulated observations
#' @param m Number of ordinal categories
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @param delta Shelter parameter
#' @param shelter Category corresponding to the shelter choice
#' @seealso \code{\link{probcubshe1}}, \code{\link{probcubshe2}}, \code{\link{probcubshe3}}
#' @examples
#' n<-300
#' m<-9
#' pai<-0.7
#' csi<-0.3
#' delta<-0.2
#' shelter<-3
#' simulation<-simcubshe(n,m,pai,csi,delta,shelter)
#' plot(table(simulation),xlab="Ordinal categories",ylab="Frequencies")
simcubshe <-
function(n,m,pai,csi,delta,shelter){
dicopai<-runif(n)<pai
dicodelta<-runif(n)<delta
cub00<-dicopai*(1+rbinom(n,m-1,1-csi))+(1-dicopai)*sample(m,n,replace=TRUE)
ord<-(1-dicodelta)*cub00+dicodelta*shelter
return(ord)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/simcubshe.R
|
#' @title Simulation routine for CUSH models
#' @aliases simcush
#' @description Generate \eqn{n} pseudo-random observations following the distribution of a CUSH
#' model without covariates.
#' @keywords distribution
#' @usage simcush(n,m,delta,shelter)
#' @export simcush
#' @import stats
#' @param n Number of simulated observations
#' @param m Number of ordinal categories
#' @param delta Shelter parameter
#' @param shelter Category corresponding to the shelter choice
#' @seealso \code{\link{probcush}}
#' @examples
#' n<-200
#' m<-7
#' delta<-0.3
#' shelter<-3
#' simulation<-simcush(n,m,delta,shelter)
#' plot(table(simulation),xlab="Ordinal categories",ylab="Frequencies")
simcush <-
function(n,m,delta,shelter){
dicodelta<-runif(n)<delta
uncert<-sample(m,n,replace=TRUE)
vett<-dicodelta*shelter+(1-dicodelta)*uncert
return(vett)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/simcush.R
|
#' @title Simulation routine for IHG models
#' @aliases simihg
#' @description Generate \eqn{n} pseudo-random observations following the given IHG distribution.
#' @keywords distribution
#' @usage simihg(n,m,theta)
#' @export simihg
#' @param n Number of simulated observations
#' @param m Number of ordinal categories
#' @param theta Preference parameter
#' @seealso \code{\link{probihg}}
#' @examples
#' n<-300
#' m<-9
#' theta<-0.4
#' simulation<-simihg(n,m,theta)
#' plot(table(simulation),xlab="Number of categories",ylab="Frequencies")
simihg <-
function(n,m,theta){
B<-(m-1)*theta/(1-theta)
psi<-1-runif(n)^(1/B)
vett<-1+rbinom(n,m-1,psi)
return(vett)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/simihg.R
|
#' @title S3 method: summary for class "GEM"
#' @description S3 method summary for objects of class \code{\link{GEM}}.
#' @aliases summary.GEM
#' @method summary GEM
#' @param object An object of class \code{\link{GEM}}
#' @param correlation Logical: should the estimated correlation matrix be returned? Default is FALSE
#' @param ... Other arguments
#' @export
#' @return Extended summary results of the fitting procedure, including parameter estimates, their standard errors and
#' Wald statistics, maximized log-likelihood compared with that of the saturated model and of a Uniform sample.
#' AIC, BIC and ICOMP indeces are also displayed for model selection. Execution time and number of exectued iterations
#' for the fitting procedure are aslo returned.
#' @import methods
#' @rdname summary.GEM
#' @keywords package
#' @examples
#' model<-GEM(Formula(MeetRelatives~0|0|0),family="cube",data=relgoods)
#' summary(model,correlation=TRUE,digits=4)
#'
################################################################
###############################################################
#summary <- function(object,...) UseMethod("summary", object)
# digits=options()$digits
summary.GEM <- function(object, correlation=FALSE, ...){
flagcov<-0
arguments<-list(...)
digits<-arguments$digits
if (is.null(digits)){
digits<-options()$digits
}
ellipsis<-object$ellipsis
m<-ellipsis[['m']]
n<-length(object$ordinal)
output<-list()
stime<-object$estimates
ordinal<-object$ordinal
freq<-tabulate(ordinal,nbins=m)
varm<- vcov(object) #as.matrix(object$varmat);
np<-length(stime)
if (isTRUE(varm==matrix(NA,nrow=np,ncol=np))==TRUE){
trvarmat<-output$ICOMP<-NA
output$errstd<-output$wald<-output$pval<-rep(NA,np)
} else {
trvarmat<-sum(diag(varm))
output$loglik<- as.numeric(logLik(object))
output$ICOMP<- -2*output$loglik + np*log(trvarmat/np) - log(det(varm))
output$errstd<-sqrt(diag(varm));
output$wald<-stime/output$errstd;
output$pval<-round(2*(1-pnorm(abs(output$wald))),digits)
}
output$loglik<-logLik(object)
output$AIC<- -2*logLik(object)+2*(np)
output$BIC<- -2*logLik(object)+log(n)*(np)
output$ellipsis<-ellipsis
output$llunif<- -n*log(m);
nonzero<-which(freq!=0)
output$logsat <- -n*log(n)+sum((freq[nonzero])*log(freq[nonzero]))
output$devian<-2*(output$logsat-object$loglik)
output$object<-object
output$n<-n
output$cormat<-NULL
if (correlation==TRUE){
output$cormat<- cormat(object)
}
StdErr<-output$errstd
Wald<-output$wald
matout<-cbind(stime,StdErr,Wald)
colnames(matout)<-c("Estimates","StdErr","Wald")
rownames(matout)<-parnames(object)
output$results<-matout
class(output)<-"summary.GEM"
print.summary.GEM <- function(x,...){
if(!is.null(cl <- x$call)) {
cat("Call:\n")
dput(cl, control = NULL)
}
ellipsis<-x$ellipsis
object<-x$object
maxiter<-object$ellipsis[['maxiter']]
family<-object$family
niter<-object$niter
m<-object$ellipsis[['m']]
stime<-object$estimates
modello<-object$formula
data<-ellipsis$data
mf<-model.frame(modello,data=data,na.action=na.omit)
n<-x$n
cat("=======================================================================","\n")
cat("=====>>>", family," model <<<===== ML-estimates via E-M algorithm ","\n")
cat("=======================================================================","\n")
cat(" m=", m," Sample size: n=",n," Iterations=", niter," Maxiter=",maxiter,"\n")
cat("=======================================================================","\n")
StdErr<-x$errstd
Wald<-x$wald
data<-object$data
listanomi<-parnames(object)
if ( family == "CUB"){
covpai<-model.matrix(modello,data=mf,rhs=1)
covcsi<-model.matrix(modello,data=mf,rhs=2)
covshe<-model.matrix(modello,data=mf,rhs=3)
if (ncol(covpai)!=0 | ncol(covcsi)!=0 | ncol(covshe)!=0){
flagcov<-1
}
if (ncol(covpai)==0){
Y<-NULL
} else {
if (NCOL(covpai)==2){
Y<-as.matrix(covpai[,-1])
colnames(Y)<-colnames(covpai)[2]
} else {
Y<-covpai[,-1]
}
}
if (ncol(covcsi)==0){
W<-NULL
} else {
if (NCOL(covcsi)==2){
W<-as.matrix(covcsi[,-1])
colnames(W)<-colnames(covcsi)[2]
} else {
W<-covcsi[,-1]
}
}
if (ncol(covshe)==0){
X<-NULL
} else {
X<-covshe[,-1]
}
if (!is.null(X) & !is.null(Y) & !is.null(W) & !is.null(object$ellipsis$shelter)){
Y<-as.matrix(Y); W<-as.matrix(W); X<-as.matrix(X);
p<-NCOL(Y);
q<-NCOL(W);
s<-NCOL(X);
mat1<-cbind(stime[1:(p+1)],StdErr[1:(p+1)],Wald[1:(p+1)])
colnames(mat1)<-c("Estimates","StdErr","Wald")
rownames(mat1)<-listanomi[1:(p+1)]
x$uncertainty<-mat1
mat2<-cbind(stime[(p+2):(p+q+2)],StdErr[(p+2):(p+q+2)],Wald[(p+2):(p+q+2)])
x$feeling<-mat2
mat3<-cbind(stime[(p+q+3):(p+q+s+3)],StdErr[(p+q+3):(p+q+s+3)],Wald[(p+q+3):(p+q+s+3)])
x$shelter<-mat3
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
cat("=======================================================================","\n")
cat("Feeling ", "\n")
colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat2)<-listanomi[(p+2):(p+q+2)]
print(mat2,digits=digits)
cat("=======================================================================","\n")
cat("Shelter effect ", "\n")
colnames(mat3)<-c("Estimates","StdErr","Wald")
rownames(mat3)<-listanomi[(p+q+3):(p+q+s+3)]
print(mat3,digits=digits)
} else if (is.null(object$ellipsis$shelter) & is.null(X) & !is.null(Y) & !is.null(W)){
Y<-as.matrix(Y); W<-as.matrix(W);
p<-NCOL(Y);
q<-NCOL(W);
mat1<-cbind(stime[1:(p+1)],StdErr[1:(p+1)],Wald[1:(p+1)])
colnames(mat1)<-c("Estimates","StdErr","Wald")
rownames(mat1)<-listanomi[1:(p+1)]
x$uncertainty<-mat1
mat2<-cbind(stime[(p+2):(p+q+2)],StdErr[(p+2):(p+q+2)],Wald[(p+2):(p+q+2)])
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat2)<-listanomi[(p+2):(p+q+2)]
x$uncertainty<-mat1
x$feeling<-mat2
cat("=======================================================================","\n")
cat("Feeling ", "\n")
print(mat2,digits=digits)
} else if (is.null(object$ellipsis$shelter) & is.null(X) & is.null(Y) & !is.null(W)){
W<-as.matrix(W);
q<-NCOL(W);
mat1<-cbind(stime[1],StdErr[1],Wald[1])
colnames(mat1)<-c("Estimates","StdErr","Wald")
rownames(mat1)<-listanomi[1]
mat2<-cbind(stime[2:(q+2)],StdErr[2:(q+2)],Wald[2:(q+2)])
colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat2)<-listanomi[2:(q+2)]
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
cat("=======================================================================","\n")
cat("Feeling ", "\n")
print(mat2,digits=digits)
x$uncertainty<-mat1
x$feeling<-mat2
} else if (is.null(object$ellipsis$shelter) & is.null(X) & !is.null(Y) & is.null(W)){
Y<-as.matrix(Y);
p<-NCOL(Y);
mat1<-cbind(stime[1:(p+1)],StdErr[1:(p+1)],Wald[1:(p+1)])
colnames(mat1)<-c("Estimates","StdErr","Wald")
rownames(mat1)<-listanomi[1:(p+1)]
mat2<-cbind(stime[(p+2)],StdErr[p+2],Wald[p+2])
colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat2)<-listanomi[p+2]
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
cat("=======================================================================","\n")
cat("Feeling ", "\n")
print(mat2,digits=digits)
x$uncertainty<-mat1
x$feeling<-mat2
} else if (is.null(object$ellipsis$shelter) & is.null(X) & is.null(Y) & is.null(W)) {
mat1<-cbind(stime[1],StdErr[1],Wald[1])
colnames(mat1)<-c("Estimates","StdErr","Wald")
mat2<-cbind(stime[2],StdErr[2],Wald[2])
colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat2)<-listanomi[2]
x$uncertainty<-mat1
x$feeling<-mat2
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
cat("=======================================================================","\n")
cat("Feeling ", "\n")
print(mat2,digits=digits)
}
}
if (family == "CUBE"){
covpai<-model.matrix(modello,data=mf,rhs=1)
covcsi<-model.matrix(modello,data=mf,rhs=2)
covphi<-model.matrix(modello,data=mf,rhs=3)
if (ncol(covpai)!=0 | ncol(covcsi)!=0 | ncol(covphi)!=0){
flagcov<-1
}
if (ncol(covpai)==0){
Y<-NULL
} else {
Y<-covpai[,-1]
}
if (ncol(covcsi)==0){
W<-NULL
} else {
W<-covcsi[,-1]
}
if (ncol(covphi)==0){
Z<-NULL
} else {
Z<-covphi[,-1]
}
if (is.null(Y)& is.null(W) & is.null(Z)){
mat1<-cbind(stime[1],StdErr[1],Wald[1])
colnames(mat1)<-c("Estimates","StdErr","Wald")
rownames(mat1)<-listanomi[1]
mat2<-cbind(stime[2],StdErr[2],Wald[2])
colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat2)<-listanomi[2]
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
cat("=======================================================================","\n")
cat("Feeling ", "\n")
print(mat2,digits=digits)
cat("=======================================================================","\n")
cat("Overdispersion ", "\n")
mat3<-cbind(stime[3],StdErr[3],Wald[3])
colnames(mat3)<-c("Estimates","StdErr","Wald")
rownames(mat3)<-listanomi[3]
print(mat3,digits=digits)
x$uncertainty<-mat1
x$feeling<-mat2
x$overdispersion<-mat3
} else if (is.null(Y)& !is.null(W) & is.null(Z)){
q<-NCOL(W)
mat1<-cbind(stime[1],StdErr[1],Wald[1])
colnames(mat1)<-c("Estimates","StdErr","Wald")
rownames(mat1)<-listanomi[1]
mat2<-cbind(stime[2:(q+2)],StdErr[2:(q+2)],Wald[2:(q+2)])
colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat2)<-listanomi[2:(q+2)]
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
cat("=======================================================================","\n")
cat("Feeling ", "\n")
print(mat2,digits=digits)
cat("=======================================================================","\n")
cat("Overdispersion ", "\n")
mat3<-cbind(stime[q+3],StdErr[q+3],Wald[q+3])
colnames(mat3)<-c("Estimates","StdErr","Wald")
rownames(mat3)<-listanomi[q+3]
print(mat3,digits=digits)
x$uncertainty<-mat1
x$feeling<-mat2
x$overdispersion<-mat3
}
else if (!is.null(Y)& !is.null(W) & !is.null(Z)){
p<-NCOL(Y)
q<-NCOL(W)
s<-NCOL(Z)
mat1<-cbind(stime[1:(p+1)],StdErr[1:(p+1)],Wald[1:(p+1)])
mat2<-cbind(stime[(2+p):(q+p+2)],StdErr[(2+p):(q+p+2)],Wald[(2+p):(q+p+2)])
colnames(mat1)<-colnames(mat2)<-c("Estimates","StdErr","Wald")
rownames(mat1)<-listanomi[1:(p+1)]; rownames(mat2)<-listanomi[(2+p):(q+p+2)]
cat("Uncertainty ", "\n")
print(mat1,digits=digits)
cat("=======================================================================","\n")
cat("Feeling ", "\n")
print(mat2,digits=digits)
cat("=======================================================================","\n")
cat("Overdispersion ", "\n")
mat3<-cbind(stime[(p+q+3):(p+q+s+3)],StdErr[(p+q+3):(p+q+s+3)],Wald[(p+q+3):(p+q+s+3)])
colnames(mat3)<-c("Estimates","StdErr","Wald")
rownames(mat3)<-listanomi[(p+q+3):(p+q+s+3)]
print(mat3,digits=digits)
x$uncertainty<-mat1
x$feeling<-mat2
x$overdispersion<-mat3
}
}
if (family == "IHG" | family =="CUSH"){
if (length(stime)>1){
flagcov<-1
}
matout<-cbind(stime,StdErr,Wald)
colnames(matout)<-c("Estimates","StdErr","Wald")
rownames(matout)<-listanomi
print(matout,digits=digits)
if (family=="IHG"){
x$preference<-matout
} else {
x$shelter<-matout
}
}
# for(i in 1:np){
# cat(nomi[i]," ",stime[i]," ",errstd[i]," ",wald[i]," ","\n")
# }
cat("=======================================================================","\n")
if (family=="CUB" & !is.null(object$ellipsis$shelter)){
covshe<-model.matrix(modello,data=mf,rhs=3)
if (ncol(covshe)==0){
X<-NULL
} else {
X<-covshe[,-1]
}
if (is.null(X)){
matout<-cbind(stime,StdErr,Wald)
colnames(matout)<-c("Estimates","StdErr","Wald")
rownames(matout)<-listanomi
print(matout,digits=digits)
#stime<-as.numeric(coef(object))
pai1<-stime[1];pai2<-stime[2];csi<-stime[3]
delta<-1-pai1-pai2
paistar<-pai1/(pai1+pai2)
stime2<-c(paistar,csi,delta)
nomi2<-c("paistar","csi","delta")
vv<-vcov(object)
esdelta<-sqrt(vv[1,1]+vv[2,2]+2*vv[1,2])
espaistar<-paistar*(1-paistar)*sqrt(vv[1,1]/(pai1^2) -2*vv[1,2]/(pai2*pai1) + vv[2,2]/pai2^2)
errstd2<-c(espaistar,StdErr[3],esdelta)
wald2<-stime2/errstd2
ErrStd<-as.numeric(errstd2)
mat2<-as.matrix(stime2)
Wald<-wald2
matout2<-cbind(mat2,ErrStd,wald2)
dimnames(matout2)<-list(nomi2,c("Estimates","StdErr","Wald"))
#matout2<-cbind(nomi2,stime2,errstd2,wald2)
# dimnames(matout2)<-list(rep("",length(nomi2)),c("Parameters", "ML-estimates" , "Std. err.", "Est./Std.err (Wald test)"))
cat("=======================================================================","\n")
cat("Alternative parameterization","\n")
print(matout2,digits=digits)
# for(i in 1:np){
# cat(nomi2[i]," ",stime2[i]," ",errstd2[i]," ",wald2[i]," ","\n")
# }
cat("=======================================================================","\n")
}
}
if (!is.null(x$cormat)){
cat("Parameters Correlation matrix","\n")
print(x$cormat)
cat("=======================================================================","\n")
}
loglik<-logLik(object)
cat("Log-lik =",round(loglik,digits=digits),"\n")
cat("Mean Log-likelihood=",round(loglik/n,digits=digits),"\n")
if (flagcov==0){
cat("Log-lik(UNIFORM) =",round(x$llunif,digits=digits),"\n")
cat("Log-lik(saturated) =",round(x$logsat,digits=digits),"\n")
cat("Deviance =",round(x$devian,digits=digits),"\n")
}
cat("-----------------------------------------------------------------------","\n")
#cat("Log-lik(Shifted-BINOMIAL) =",round(llsb,digits=8),"\n")
#cat("-----------------------------------------------------------------------","\n")
cat("AIC =",round(x$AIC,digits=digits),"\n")
cat("BIC =",round(x$BIC,digits=digits),"\n")
cat("ICOMP =",round(x$ICOMP,digits=digits),"\n")
cat("=======================================================================","\n")
cat("Elapsed time=",object$time,"seconds","=====>>>",date(),"\n")
cat("=======================================================================","\n")
class(x)<-"summary.GEM"
#return(list(x$uncertainty,x$feeling,x$overdispersion,x$shelter,x$preference))
} ## chiude definizione print.summary
print(output)
invisible(output$results)
#invisible(output)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/summary.R
|
#' @title Evaluation of the Orientation Services 2002
#' @description A sample survey on students evaluation of the Orientation services was conducted across the
#' 13 Faculties of University of Naples Federico II in five waves: participants were asked to express their ratings
#' on a 7 point scale (1 = "very unsatisfied", 7 = "extremely satisfied").
#' Here dataset collected during 2002 is loaded.
#' @aliases univer
#' @usage data(univer)
#' @format The description of subjects' covariates is:
#' \describe{
#' \item{\code{Faculty}}{A factor variable, with levels ranging from 1 to 13 indicating the coding
#' for the different university faculties}
#' \item{\code{Freqserv}}{A factor with levels: 0 = for not regular users, 1 = for regular users}
#' \item{\code{Age}}{Variable indicating the age of the respondent in years}
#' \item{\code{Gender}}{A factor with levels: 0 = man, 1 = woman}
#' \item{\code{Diploma}}{A factor with levels: 1 = classic studies, 2 = scientific studies, 3 = linguistic,
#' 4 = Professional, 5 = Technical/Accountancy, 6 = others}
#' \item{\code{Residence}}{A factor with levels: 1 = city NA, 2 = district NA, 3 = others}
#' \item{\code{ChangeFa}}{A factor with levels: 1 = changed faculty, 2 = not changed faculty}
#' }
#' Analyzed ordinal variables (Likert ordinal scale):
#' 1 = "extremely unsatisfied", 2 = "very unsatisfied", 3 = "unsatisfied", 4 = "indifferent", 5 = "satisfied", 6 = "very satisfied",
#' 7 = "extremely satisfied"
#' \describe{
#' \item{\code{Informat}}{Level of satisfaction about the collected information}
#' \item{\code{Willingn}}{Level of satisfaction about the willingness of the staff}
#' \item{\code{Officeho}}{Judgment about the Office hours}
#' \item{\code{Competen}}{Judgement about the competence of the staff}
#' \item{\code{Global}}{Global satisfaction}
#' }
#' @keywords datasets
#' @details
#' \describe{
#' Period of data collection: 2002 \cr
#' Mode of collection: questionnaire \cr
#' Number of observations: 2179 \cr
#' Number of subjects' covariates: 7 \cr
#' Number of analyzed items: 5
#' }
"univer"
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/univer.R
|
#' @title Variance-covariance matrix of a CUB model without covariates
#' @description Compute the variance-covariance matrix of parameter estimates of a CUB model without covariates.
#' @aliases varcovcub00
#' @usage varcovcub00(m, ordinal, pai, csi)
#' @param m Number of ordinal categories
#' @param ordinal Vector of ordinal responses
#' @param pai Uncertainty parameter
#' @param csi Feeling parameter
#' @export varcovcub00
#' @details The function checks if the variance-covariance matrix is positive-definite: if not,
#' it returns a warning message and produces a matrix with NA entries.
#' @seealso \code{\link{probcub00}}
#' @keywords internal
#' @references
#' Piccolo D. (2006), Observed Information Matrix for MUB Models. \emph{Quaderni di Statistica},
#' \bold{8}, 33--78,
#' @examples
#' data(univer)
#' m<-7
#' ordinal<-univer[,12]
#' pai<-0.87
#' csi<-0.17
#' varmat<-varcovcub00(m, ordinal, pai, csi)
varcovcub00 <-
function(m,ordinal,pai,csi){
if (is.factor(ordinal)){
ordinal<-unclass(ordinal)
}
vvi<-(m-ordinal)/csi-(ordinal-1)/(1-csi)
ui<-(m-ordinal)/(csi^2)+(ordinal-1)/((1-csi)^2)
pri<-probcub00(m,pai,csi)
qi<-1/(m*pri[ordinal])
qistar<-1-(1-pai)*qi
qitilde<-qistar*(1-qistar)
i11<-sum((1-qi)^2)/(pai^2)
i12<- -sum(vvi*qi*qistar)/pai
i22<-sum(qistar*ui-(vvi^2)*qitilde)
####################################### Information matrix
matinf<-matrix(c(i11,i12,i12,i22),nrow=2,byrow=T)
####################################### Variance-covariance matrix
if(any(is.na(matinf))==TRUE){
warning("ATTENTION: NAs produced")
varmat<-matrix(NA,nrow=2,ncol=2)
} else {
if(det(matinf)<=0){
warning("ATTENTION: Variance-covariance matrix NOT positive definite")
varmat<-matrix(NA,nrow=2,ncol=2)
} else {
varmat<-solve(matinf)
}
}
return(varmat)
}
|
/scratch/gouwar.j/cran-all/cranData/CUB/R/varcovcub00.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.