Package {ConsRankClass}


Type: Package
Title: Classification and Clustering of Preference Rankings
Version: 1.1.0
Date: 2026-11-26
Maintainer: Antonio D'Ambrosio <antdambr@unina.it>
LinkingTo: Rcpp
Depends: ConsRank (≥ 3.1)
Imports: Rcpp, janitor, methods, pracma, rlist, proxy, smacof, gtools, graphics, grDevices, grid, lattice, stats, utils
Description: Tree-based classification and soft-clustering method for preference rankings, with tools for external validation of fuzzy clustering, and Kemeny-equivalent augmented unfolding. It contains the recursive partitioning algorithm for preference rankings, non-parametric tree-based method for a matrix of preference rankings as a response variable. It contains also the distribution-free soft clustering method for preference rankings, namely the K-median cluster component analysis (CCA). The package depends on the 'ConsRank' R package. Options for validate the tree-based method are both test-set procedure and V-fold cross validation, with the s-SE rule. In the trees, the class of a node can be computed with the BOLT algorithm and constrained to a given number of buckets, to a given pattern of bucket sizes or to a top-k list; the impurity can be the pairwise impurity of D'Ambrosio and Heiser (2016) or the distance of the judges from the class of the node (median impurity), and the objects not ranked by the judges can be tied in the last position or treated as unknown. Descriptive tools: marginal and pairs matrices, projection of the rankings on the permutation polytope, clustering of the objects, multidimensional scaling of the judges, each with its plot (base graphics or 'lattice'). The package contains the routines to compute the adjusted concordance index (a fuzzy version of the adjusted rand index) and the normalized degree of concordance (the corresponding fuzzy version of the rand index). The package also contains routines to perform the Kemeny-equivalent augmented unfolding. The MDS engine is either the function 'smacofSym' from the package 'smacof' or the function mdscale() of this package, metric and non-metric multidimensional scaling with the criteria of the 'MATLAB' function of the same name (stress, sstress, metric stress, metric sstress, Sammon mapping, strain). It also contains distances between complete rankings (Kendall, Cayley, Hamming, Ulam, Spearman footrule, Spearman), the Mallows (distance-based) model for any of these distances, with exact normalising constants, maximum likelihood estimation and exact simulation, mixtures of distance-based models fitted by the EM algorithm with model selection by BIC and ICL, and distance-based tree models in which a Mallows model is fitted within each node (also for top-k partial rankings). Essential references: D'Ambrosio, A., Vera, J.F., and Heiser, W.J. (2021) <doi:10.1080/00273171.2021.1899892>; D'Ambrosio, A., Amodio, S., Iorio, C., Pandolfo, G., and Siciliano, R. (2021) <doi:10.1007/s00357-020-09367-0>; D'Ambrosio, A., and Heiser, W.J. (2019) <doi:10.1007/s41237-018-0069-5>; D'Ambrosio, A., and Heiser W.J. (2016) <doi:10.1007/s11336-016-9505-1>; Hullermeier, E., Rifqi, M., Henzgen, S., and Senge, R. (2012) <doi:10.1109/TFUZZ.2011.2179303>; Murphy, T.B., and Martin, D. (2003) <doi:10.1016/S0167-9473(02)00165-2>; Lee, P.H., and Yu, P.L.H. (2010) <doi:10.1016/j.csda.2010.01.027>; Marden, J.I. (1995) <ISBN:0412995212>.
License: GPL-3
Encoding: UTF-8
Config/roxygen2/version: 8.1.0
NeedsCompilation: yes
Packaged: 2026-11-26 11:36:00 UTC; Antonio
Author: Antonio D'Ambrosio [aut, cre], Luca Coraggio [ctb] (descriptive tools (marginals, pairmatrix, rankproj, objclust, judgemds) and mdscale)
Repository: CRAN
Date/Publication: 2026-11-26 16:10:07 UTC

European Values Studies (EVS) data

Description

Sub-sample of 1911 respondents of the survey conducted in 1999 in 32 countries, from the data analyzed by Vermunt (2003).

Usage

data("EVS")

Format

The format is: List of 3

$ data:'data.frame': 1911 obs. of 11 variables:

country, gender ,yearbird, mstatus (marital status), eduage (age of education completion), employment (Employment status: ordinal scale 1-8), householdinc (Household income: ordinal scale 1-10), A (Maintain order in Nation),Give people more say in Government decisions, (C) Fight rising prices, (D) Protect freedom of speech.

$ predictors:'data.frame' with all the predictors

$ rankings : matrix with the preferences for "A" (Maintain order in Nation), "B" (Give people more say in Government decisions), "C" (Fight rising prices), "D" (Protect freedom of speech).

Details

Rankings were obtained by applying the post-materialism scale developed by Inglehart (1977). The scale is based upon an experiment of the type “pick 2 out of 4” most important political goals for your Governments: each row ranks two goals (1 and 2), and the two goals not chosen are NaN. ranktree treats them as tied in the last position (unranked = "last", the default, as in D'Ambrosio and Heiser, 2016) or, with impurity = "median", as objects whose order is unknown (unranked = "unknown"); see ranktreecontrol. For the other functions (e.g., cca) replace the NaNs with 3 before using the rankings. About the predictors, the coding of the Countries are: G1 (Austria, Denmark, Netherlands, Sweden), G2 (Belgium, Croatia, France, Greece, Ireland, Northern Ireland, Spain), G3 (Bulgaria, Czechia, East Germany, Finland, Iceland, Luxembourg, Malta, Portugal, Romania, Slovenia, West Germany), G4 (Belarus, Estonia, Hungary, Latvia, Lithuania, Poland, Russia, Slovakia, Ukraine). Coding of predictor "mstatus" are: mar (married), wid (widowed), div (divorced), sep (separated), nevm (never married).

Source

http://statisticalinnovations.com/technicalsupport/choice_datasets.html

References

Vermunt, J. K. (2003). Multilevel latent class models. Sociological Methodology, 33(1), 213–239.

Inglehart, R. (1977). The silent revolution: Changing values and political styles among Western Publics. Princeton, NJ: Princeton University Press.

D'Ambrosio, A., and Heiser W.J. (2016). A recursive partitioning method for the prediction of preference rankings based upon Kemeny distances. Psychometrika, vol. 81 (3), pp.774-94.

Examples

data(EVS)

# EVS$rankings[is.na(EVS$rankings)] <- 3 #place unranked objects in a tie to the third position
# ccares <- cca(EVS$rankings,4) #solution with 4 components


Irish Election data set

Description

An opinion poll conducted by Irish Marketing Surveys one month prior to the election in 1997. Interviews were conducted on about 1100 respondents, drawn from 100 sampling areas. Interviews took place at randomly located homes, with respondents selected according to a socioeconomic quota. A range of sociological questions was asked of each respondent, as was their voting preference, if any, for each of the candidates.

Usage

data("Irish")

Format

The format is: List of 3

$ IrishElection: 'data.frame': 1083 obs. of 11 variables: Gender (male, housewife, nonhousewife), marital status (single, married, separated), age, socialclass (five unordered categories), Area (rural, city, town), government satisfaction (no opinion,m satisfied, dissatisfied), Bano , Roch, McAl, Nall, Scal

$ predictors :'data.frame' with all the predictors

$ rankings : matrix with the preferencres for "Bano" "Roch" "McAl" "Nall"

Details

In the original version of the data, the ranking matrix contains NAs. Here, NAs are replaced with the number 7, to indicate that all the non-stated preferences are in a tie at the last position (see D'Ambrosio and Heiser, 2016). For details about the data set see Gormley and Murphy, 2008.

Source

https://projecteuclid.org/journals/annals-of-applied-statistics/volume-2/issue-4/A-mixture-of-experts-model-for-rank-data-with/10.1214/08-AOAS178.full?tab=ArticleLinkSupplemental

References

Gormley, I.C., and Murphy, T.B. (2008). A mixture of experts model for rank data withapplications in election studies. Annals of Applied Statistics 2(4): 1452-1477. DOI: 10.1214/08-AOAS178

D'Ambrosio, A., and Heiser W.J. (2016). A recursive partitioning method for the prediction of preference rankings based upon Kemeny distances. Psychometrika, vol. 81 (3), pp.774-94. DOI: 10.1007/s11336-016-9505-1.

Examples

data(Irish)

University rankings dataset.

Description

University rankings dataset was analysed by Dittrich, Hatzinger and Katzenbeisser (1998) to investigate paired comparison data concerning European universities and student's characteristics with the goal to show that university rankings are different for different groups of students. Here both raw data (with paired comparisons) and the version with rankings are preesented (see details). A survey of 303 students studying at the Vienna University of Economics was carried out to examine the student's preference of six universities, namely London, Paris, Milan, St. Gallen, Barcelona and Stockholm. The data set contains 23 variables. The first 15 digits in each row indicate the preferences of a student. For a given comparison, responses were coded by 1 if the first preference was preferred, by 2 if the second university was preferred, and by 3 if universities are tied. All rows containing missing ranked Universities were skipped.

Usage

data("Univranks")

Format

The format is: List of 3

$ rawdata: 'data.frame': 212 obs. of 23 variables: the first 15 are the paired comparisons coded as follows: (1: the first is preferred to the second; 2: the second is preferred to the fisrt; 3 tied)

$ LP : comparison of London to Paris

$ LM : comparison of London to Milan

$ PM : comparison of London to Milan

$ LSg : comparison of London to St. Gallen

$ PSg : comparison of Paris to St. Gallen

$ MSg : comparison of Milan to St. Gallen

$ LB : comparison of London to Barcelona

$ PB : comparison of Paris to Barcelona

$ MB : comparison of Milan to Barcelona

$ SgB : comparison of St. Gallen to Barcelona

$ LSt : comparison of London to Stockholm

$ PSt : comparison of Paris to Stockholm

$ MSt : comparison of Milan to Stockholm

$ SgSt: comparison of St. Gallen to Stockholm

$ BSt : comparison of Barcelona to Stockholm

$ Stud: Factor w/ 2 levels "commerce","other"

$ Eng : Factor w/ 2 levels "good","poor""

$ Fra : Factor w/ 2 levels "good","poor"

$ Spa : Factor w/ 2 levels "good","poor"

$ Ita : Factor w/ 2 levels "good","poor"

$ Wor : Factor w/ 2 levels "no","yes"

$ Deg : Factor w/ 2 levels "no","yes"

$ Sex : Factor w/ 2 levels "female","male"

$ predictors:'data.frame': 212 obs. of 8 variables( the last 8 variables of the "rawdata" dataframe

$ rankings : matrix of preference rankings. The columns are: "L" (London), "P" (Paris), "M" (Milan), "Sg" (St. Gallen), "B" (Barcerlona), "St" (Stockholm)

Details

To obtain the preference rankings from the paired comparisons the procedure has been the following: the first row of the raw data is [1 3 2 1 2 1 1 2 1 1 1 2 1 1 2]. London is preferred to Paris, St. Gallen, Barcelona, Stockholm (LP, LM, LSg, LB and LSt are always equal to 1), and there is no preference between London and Milan (they are tied); Milan is preferred to Paris (PM = 2), St. Gallen, Barcelona and Stockholm; and so on. The first ordering is then <{L M} Sg St B P> corresponding to a ranking [1,5,1,2,4,3], where the columns indicate L P M Sg B St.

Source

http://www.blackwellpublishers.co.uk/rss

References

Dittrich, R., Hatzinger, R., and Katzenbeisser, W. (1998). Modelling the effect of subject-specific covariates in paired comparison studies with an application to university rankings. Journal of the Royal Statistical Society: Series C (Applied Statistics), 47(4), 511-525. DOI: 10.1111/1467-9876.00125

D'Ambrosio, A. (2008). Tree based methods for data editing and preference rankings. Ph.D. thesis, University of Naples Federico II. https://www.doi.org/10.6092/UNINA/FEDOA/2746

Examples

data(Univranks)

Kemeny-equivalent augmented dissimilarity matrix

Description

Kemeny-equivalent augmented dissimilarity matrix

Usage

augmatrix(X)

Arguments

X

A n by m data matrix, in which there are n judges and m objects to be judged. Each row is a ranking of the objects which are represented by the columns.

Details

First the matrix is transformed with the tau_X rank correlation coeficient, then it is normalized. The output contains:

Delta the augmented dissimilarity matrix
Interaction the submatrix containnig the interactions individuals-items
Objects the submatrix containing the within-items proximities
Indiv the submatrix containing the within-individuals proximities
beta the beta parameter
alpha the alpha parameter
csi the csi parameter
res the resume of th eaugmentation in terms of:
TauX tau_x rank correlation coefficient
Kendall kendall rank correlation coefficient
Spearman Spearman correlation coefficient

Value

A list containing the dissimilarity matrix and othe information about the augmented matrix. See details for detailed information.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

D'Ambrosio, A., Vera, J. F., & Heiser, W. J. (2022). Avoiding degeneracies in ordinal unfolding using Kemeny-equivalent dissimilarities for two-way two-mode preference rank data. Multivariate Behavioral Research, 57(4), 679-699.


K-Median Cluster Component Analysis

Description

K-Median Cluster Component Analysis, a distribution-free soft-clustering method for preference rankings.

Usage

cca(X, k, control = ccacontrol(...), ...)

Arguments

X

A n by m data matrix containing preference rankings, in which there are n judges and m objects to be judged. Each row is a ranking of the objects which are represented by the columns.

k

The number of cluster components

control

a list of options that control details of the cca algorithm governed by the function ccacontrol. The options govern maximum number of iterations of cca (itercca=1 is the default), the algorithm chosen to compute the median ranking (default, "quick"), and other options related to the consrank algorithm, which is called by cca

...

arguments passed bypassing ccacontrol

Details

The user can use any algorithm implemented in the consrank function from the ConsRank package ("BB", "quick", "fast", "decor" or "BOLT", see ccacontrol). All algorithms allow the user to set the option 'full=TRUE' if the median ranking(s) must be searched in the restricted space of permutations instead of in the unconstrained universe of rankings of n items including all possible ties. There are two classification uncertainty measures: Us and Uprods. "Us" is the geometric mean of the membership probabilities of each individual, normalized in such a way that in the case of maximum uncertainty Us=1. "Ucca" is the average of all the "Us". "Uprods" is the product of the membership probabilities of each individual, normalized in such a way that in the case of maximum uncertainty Uprods=1. "Uprodscca" is the average of all the "Uprods".

If two cluster centres coincide during the iterations, they would receive the same membership probabilities and remain equal, so that the solution would have fewer than k clusters. In that case each duplicate centre is replaced by the ranking of the judge farthest from the other centres (the judge whose Kemeny distance from its closest centre is the largest), and the iterations go on; at most 10 re-initializations are made in each start. A judge at distance zero from two or more coincident centres gets equal membership probabilities on them. A start whose final centres are not all distinct is flagged as degenerate; with itercca > 1 the best start is chosen among the non-degenerate ones, if any.

Value

An object of the class "cca". It contains:

pk the membership probability matrix
clc cluster centers
oclc cluster centers in terms of orderings
idc crisp partition: id of the cluster component associated with the highest membership probability
Hcca Global homogeneity measure (tau_X rank correlation coefficient)
hk Homogeneity within cluster
props estimated proportion of cases within cluster
Us Uncertainty measure per-individual (see details)
Ucca Global uncertainty measure
Uprods Uncertainty measure per-individual (see details)
Uprodscca Global uncertainty measure
consrankout complete output of rank aggregation algorithm, containing eventually multiple median rankings
degenerate TRUE if two or more cluster centres coincide (fewer than k distinct clusters)
reinit number of re-initializations of coincident centres (see details)

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

D'Ambrosio, A. and Heiser, W.J. (2019). A Distribution-free Soft Clustering Method for Preference Rankings. Behaviormetrika , vol. 46(2), pp. 333–351, DOI: 10.1007/s41237-018-0069-5

Heiser W.J., and D'Ambrosio A. (2013). Clustering and Prediction of Rankings within a Kemeny Distance Framework. In Berthold, L., Van den Poel, D, Ultsch, A. (eds). Algorithms from and for Nature and Life.pp-19-31. Springer international. DOI: 10.1007/978-3-319-00035-0_2.

Ben-Israel, A., and Iyigun, C. (2008). Probabilistic d-clustering. Journal of Classification, 25(1), pp.5-26. DOI: 10.1007/s00357-008-9002-z

See Also

ccacontrol

ranktree

Examples


data(Irish)
set.seed(135) #for reproducibility
# CCA with four components
ccares <- cca(Irish$rankings, 4, itercca=10)
summary(ccares)




Utility function

Description

Utility function to use to set the control arguments of cca

Usage

ccacontrol(
  algorithm = "quick",
  full = FALSE,
  itercca = 1,
  consrankitermax = 10,
  np = 15,
  gl = 100,
  ff = 0.4,
  cr = 0.9,
  proc = FALSE,
  ps = FALSE
)

Arguments

algorithm

The algorithm used to compute the median ranking. One among "BB", "quick" (default), "fast", "decor" and "BOLT" (the name is matched ignoring the case). "BOLT" is the deterministic heuristic of bolt, fast also with many objects

full

If TRUE, the median ranking is searched in the restricted space of permutations (rankings without ties); if FALSE (default), in the universe of rankings of the objects including all the possible ties

itercca

Number of iterations of cca

consrankitermax

Number of iterations for "fast" and "decor" algorithms. itermax=10 is the default option.

np

(for "decor" only) the number of population individuals. np=15 is the default option.

gl

(for"decor" only) generations limit, maximum number of consecutive generations without improvement. gl=100 is the default option.

ff

(for"decor" only) the scaling rate for mutation. Must be in [0,1]. ff=0.4 is the default option.

cr

(for"decor" only) the crossover range. Must be in [0,1]. cr=0.9 is the default option.

proc

(for "BB" only) proc=TRUE allows the branch and bound algorithm to work in difficult cases, i.e. when the number of objects is larger than 15 or 25. proc=FALSE is the default option

ps

If PS=TRUE, on the screen some information about how many branches are processed are displayed. Default value: FALSE

Value

A list containing all the control parameters

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

cca


Distribution of a ranking distance under the uniform model

Description

Number of permutations of M objects at each possible distance from a fixed ranking (by right-invariance it does not depend on that ranking). It is the basis of the normalising constant of the Mallows model.

Usage

distfreq(M, dist = "kendall")

Arguments

M

Number of objects.

dist

The distance (see rankdist).

Details

Exact computation: Mahonian numbers (Kendall), Stirling numbers of the first kind (Cayley), binomial coefficients times derangement numbers (Hamming), sums of squared numbers of standard Young tableaux via the Robinson-Schensted correspondence (Ulam, M \le 50), dynamic programming over subsets (footrule and Spearman, M \le 14).

Value

A data frame with the distance values d, the number of permutations count and its logarithm logcount.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mallowsnorm, rankdist

Examples

distfreq(5, "kendall")
sum(distfreq(6, "ulam")$count) == factorial(6)


Normalized Degree of Concordance (NDC) and Adjusted Concordance Index (ACI)

Description

Given two fuzzy (Ruspini) partitions, it compute the NDC and the ACI. NDC is the fuzzy version of the Rand Index, as well as ACI is the fuzzy version of the Adjusted Rand Index

Usage

fuzzyconcordance(P, Q, nperms = NULL)

Arguments

P

A fuzzy partition. It has to be a matrix with n rows and k columns. Each column is expression of the degree of membership of the i-th row over the k partitions (see details).

Q

A fuzzy partition. It has to be a matrix with n rows and h columns. Each column is expression of the degree of membership of the i-th row over the h partitions (see details).

nperms

NULL (default): the expected NDC under random permutations, needed by ACI, is computed exactly. A number: it is estimated with nperms random permutations, as in versions <= 1.1.0 (slower, kept for reproducibility).

Details

Both P and Q, or only one of those, can be crisp (or hard) partitions. In this case, each row must contain either 0 or 1, and the sum of the i-th row must be 1. In other words, either P or Q (or both) are expressed in terms of dummy coding. If both partitions are crisp, then NDC is equal to Rand Index and ACI is equal to Adjusted Rand Index. This function can be used to externally validate the output of any fuzzy clustering method

ACI = (NDC - E[NDC]) / (1 - E[NDC]), where E[NDC] is the expected NDC when the rows of Q are randomly permuted. Under a random permutation each pair of units of P is matched with a pair of units of Q drawn uniformly, so E[NDC] = 1 - mean |e_P(p) - e_Q(q)| over all couples of pairs (p, q). This mean is computed exactly in O(N log N), N = n(n-1)/2, by sorting the two sets of pairwise concordances: it is the limit of the permutation estimate when nperms goes to infinity.

Value

A list containing:

ACI the Adjusted Concordance Index
NDC the Normalized Degree of Concordance

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

D’Ambrosio, A., Amodio, S., Iorio, C., Pandolfo, G. and Siciliano, R. (2021). Adjusted Concordance Index: an Extension of the Adjusted Rand Index to Fuzzy Partitions. Journal of Classification vol. 38(1), pp. 112–128 (2021). DOI: 10.1007/s00357-020-09367-0

Hullermeier, E., Rifqi, M., Henzgen, S., and Senge, R. (2012). Comparing fuzzy partitions: a generalization of the Rand index and related measures. IEEE Transactions on Fuzzy Systems, 20(3), 546–556. DOI: 10.1109/TFUZZ.2011.2179303

See Also

cca

Examples

#two random fuzzy partitions
P = rbind(c(0.5259,  0.1656,    0.3085),
c(0.5623,    0.1036,    0.3341),
c(0.2508,    0.1849,    0.5643),
c(0.5654,    0.1934,    0.2413),
c(0.4529,    0.1679,    0.3792),
c(0.2390,    0.1758,    0.5852),
c(0.3114,    0.1743,    0.5143),
c(0.4188,    0.1392,    0.4420),
c(0.5830,    0.1655,    0.2514),
c(0.5860,    0.1171,    0.2969),
c(0.2630,    0.1706,    0.5664),
c(0.5882,    0.1032,    0.3086),
c(0.5829,    0.1277,    0.2894),
c(0.3942,    0.1046,    0.5012),
c(0.5201,    0.1097,    0.3702),
c(0.2568,    0.1823,    0.5609),
c(0.3687,    0.1695,    0.4618),
c(0.5663,    0.1317,    0.3020),
c(0.5169,    0.1950,    0.2881),
c(0.5838,    0.1034,    0.3128))

Q = rbind(c(0.4494,    0.3755,    0.1751),
c(0.5219,    0.3526,    0.1255),
c(0.3432,    0.5062,    0.1506),
c(0.3120,    0.5181,    0.1699),
c(0.5362,    0.2747,    0.1891),
c(0.4082,    0.3959,    0.1959),
c(0.4670,    0.3782,    0.1547),
c(0.4276,    0.4585,    0.1139),
c(0.4013,    0.4837,    0.1149),
c(0.3724,    0.5019,    0.1258),
c(0.5055,    0.3104,    0.1841),
c(0.4027,    0.4719,    0.1254),
c(0.3565,    0.4620,    0.1814),
c(0.6106,    0.2650,    0.1244),
c(0.5595,    0.2476,    0.1929),
c(0.4657,    0.3993,    0.1350),
c(0.2964,    0.5839,    0.1197),
c(0.5387,    0.3362,    0.1251),
c(0.4043,    0.4341,    0.1616),
c(0.5631,    0.2895,    0.1473))
         
ci <- fuzzyconcordance(P,Q) 

#generate a random fuzzy partition with two components (clusters)
Q2 <- matrix(runif(20),ncol=1)
Q2 <- cbind(Q2,1-Q2)

ci2 <- fuzzyconcordance(P,Q2)

#generate a random crisp partition
P2 <- t(rmultinom(20,1,c(0.3,0.3,0.4)))

ci3 <- fuzzyconcordance(P2,Q)
#--------------------
## Not run: 
# install.packages("Rankcluster")
library("Rankcluster") # model-based clustering algorithm for
                     #  ranking data by Biernacki and Jacques (2013)
                     #  <doi:10.1016/j.csda.2012.08.008>
data(APA)
set.seed(136) #for reproducibility
rcres <- rankclust(APA$data,K=3)  # solution with 3 centers, it takes about 75 seconds
##
ccares <- cca(APA$data,k=3) #solution with 3 components, it takes about 7 seconds
##
ci <- fuzzyconcordance(rcres[3]@tik,ccares$pk)
ci$ACI  # 0.0226 means that the two partitions are similar (see NDC below), 
        # but their similarity is mainly due to chance
ci$NDC

## End(Not run)
 
  
    

Determine a tree from the main tree-based structure

Description

Given a tree belonging to the class "ranktree", determine a subtree with a given number of terminal nodes

Usage

getsubtree(Tree, cut, tokeep = NULL)

Arguments

Tree

An object of the class "ranktree" coming form te function ranktree

cut

The maximum number of terminal nodes that the Tree must have

tokeep

parameter invoked by other internal functions

Details

If the pruning sequence returns a series of subtrees with, say, 1,2,4,7,9 terminal nodes and the user set cut=8, the function extract the subtree with 7 terminal nodes.

Value

An object of the class "ranktree", containing the same information of the output of the function ranktree

Author(s)

Antonio D'Ambrosio antdambr@unina.it

Examples


data("Univranks")
tree <- ranktree(Univranks$rankings,Univranks$predictors,num=50)
#see how many terminal nodes have the trees compomimg the nested sequence of subtrees
infoprun <- tree$pruneinfo$termnodes
#select the tree with, say, 6 terminal nodes
tree6 <- getsubtree(tree,6)



Multidimensional scaling of the judges

Description

Represents the judges in a low-dimensional space by multidimensional scaling (mdscale) of the Kemeny distances between their rankings. Judges with the same ranking share a point. Use plot to display the configuration.

Usage

judgemds(X, wk = NULL, p = 2, weighted = TRUE, ...)

Arguments

X

A n by m data matrix (or data frame), in which there are n judges and m objects to be judged. Each row is a ranking of the objects, which are represented by the columns; ties are allowed, and so are missing values (NA or NaN) for objects not ranked by a judge (e.g. top-k partial rankings), which are treated as tied in the last position.

wk

Optional vector of n non-negative weights (e.g. the frequencies of the distinct rankings in the rows of X). Default NULL: every judge has weight 1.

p

The number of dimensions. Default 2.

weighted

If TRUE (default), the pair of distinct rankings i, j has weight w_i w_j in the criterion, where w_i is the number (total weight) of judges giving ranking i, so the configuration represents the judges rather than the distinct rankings; if FALSE all the pairs of distinct rankings have the same weight.

...

Other arguments passed to mdscale (e.g. criterion, start, replicates, control).

Details

The scaling is computed on the distinct rankings only, whose number is often much smaller than the number of judges, with the Kemeny distances between them (ConsRank::kemenyd). The default criterion is the one of mdscale ("sstress"). The output of mdscale is returned too, so that, e.g., its Shepard diagram can be plotted with plot(x$mds, type = "shepard"). To place the objects in the same space as the judges use kunfolding.

Value

An object of class judgemds, a list with:

conf the configuration of the distinct rankings (one row each)
rankings the distinct rankings, in standard form (1, 2, ... for the buckets)
weights the number (total weight) of judges with each distinct ranking
idx the distinct ranking of each row of X (NA for rows with zero weight)
wk the weights of the rows of X (1 if not given)
mds the output of mdscale
nj the number of judges (the sum of the weights)
items the names of the objects

Author(s)

Luca Coraggio luca.coraggio@unina.it

See Also

plot.judgemds, mdscale, rankproj, kunfolding

Examples

data(Univranks)
jm <- judgemds(Univranks$rankings)
jm
plot(jm, groups = Univranks$predictors$Stud)


Kemeny-equivalent augmented unfolding

Description

Kemeny-equivalent augmented unfolding.

Usage

kunfolding(X, p = 2, control = mdscontrol(...), ...)

Arguments

X

A n by m data matrix, in which there are n judges and m objects to be judged. Each row is a ranking of the objects which are represented by the columns.

p

the dimensionality of the solution. Default p=2

control

a list of options that control details of the kunfolding model governed by the function mdscontrol. The options govern the MDS model ("ordinal" or "metric"), the initial configuration ("torgerson", "random" or "user"), the transformation ("primary", "secondary", "tertiary","spline","ratio", "interval","none"), the set of weights, and other related options

...

arguments passed bypassing mdscontrol

Details

The MDS engine is smacofSym from smacof (default) or mdscale from this package, which minimises the criteria of the MATLAB function mdscale (choose it with engine = "mdscale" in mdscontrol). The output consists in a object of the class "kunfolding". It contains:

rawstress raw stress
nrawstress normalized raw stress
stress1 Stress-1
rowcoord row (individuals) coordinates
colcord column (items) coordinates
dhat dhat
dij configuration distance
shepardD DeSarbo I Index
kendallfit Kendall tau_b between transformed and fitted proximities
tauxfit Tau_X between transformed and fitted proximities
avgrecov Averaged recovery measure between raw preference data and fitted proximities
avgedpearson Averaged Pearson correlation between raw preference data and fitted proximities
avgspearman Averaged Spearman rho between raw preference data and fitted proximities
avgkendall Averaged Kendall taub between raw preference data and fitted proximities
avgtaux Averaged Tau_X between raw preference data and fitted proximities
resume Resume meausures
resumerec tab Resume of recovery measures
resumeaug Resume of augmentation matrix
kDelta Kemeny equivalent dissimilarity matrix
beta beta parameter
alpha alpha parameter
interactions n x m interaction submatrix
csi csi parameter
mdssol mds solution as returned by smacof package
n_i number of individuals
n_c number of items
tots total
model mds model
transf transformation used
engine MDS engine ("smacof" or "mdscale")
criterion criterion minimised by mdscale (NULL with smacof)

Value

An object of the class kunfolding. See details for detailed information.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

D'Ambrosio, A., Vera, J. F., & Heiser, W. J. (2022). Avoiding degeneracies in ordinal unfolding using Kemeny-equivalent dissimilarities for two-way two-mode preference rank data. Multivariate Behavioral Research, 57(4), 679-699.

See Also

augmatrix

Examples

data("breakfast", package="smacof")
unfout <- kunfolding(breakfast)
itemsl <- colnames(breakfast)
plot(unfout,labs=itemsl)


Utility function

Description

A utility function completing the output of the function ranktree.

Usage

layouttree(Tree)

Arguments

Tree

an object of the class "ranktree"

Value

an object of the class "ranktree" completing the output of the function ranktree

Author(s)

Antonio D'Ambrosio antdambr@unina.it


Log-likelihood of a mallows object

Description

Log-likelihood of a mallows object

Usage

## S3 method for class 'mallows'
logLik(object, ...)

Arguments

object

An object of class "mallows".

...

Not used.

Value

An object of class "logLik" (one degree of freedom: the center is not counted), usable with AIC and BIC.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mallows


Log-likelihood of a mixdbm object

Description

Log-likelihood of a mixdbm object

Usage

## S3 method for class 'mixdbm'
logLik(object, ...)

Arguments

object

An object of class "mixdbm".

...

Not used.

Value

An object of class "logLik" with the degrees of freedom of the model (see mixdbm), usable with AIC and BIC.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbm


Mallows (distance-based) model for complete rankings

Description

Maximum likelihood estimation of the Mallows model P(r) = C(\lambda) \exp\{-\lambda d(r, R)\} with center (modal ranking) R and precision \lambda, for any of the distances of rankdist.

Usage

mallows(
  X,
  dist = "kendall",
  center = NULL,
  weights = NULL,
  centermethod = c("auto", "exhaustive", "local", "bb"),
  lambdamax = 50
)

Arguments

X

A n by M matrix of complete rankings (rank of object j in column j).

dist

The distance: "kendall" (default, the classical Mallows model), "cayley", "hamming", "ulam", "footrule", "spearman" or "spearmansq".

center

Optional known center: if given only \lambda is estimated.

weights

Optional non-negative case weights.

centermethod

Method for the center (see mallowscenter).

lambdamax

Upper bound for \lambda.

Details

The MLE of the center is the median ranking with respect to the chosen distance (see mallowscenter); given the center, the MLE of \lambda solves E_\lambda[d] = \bar d. The standard error of \lambda is computed from the Fisher information n \, Var_\lambda[d], conditionally on the estimated center. The normalising constant is exact (closed forms for Kendall and Cayley; for Ulam M \le 50, for footrule and Spearman M \le 14). As in mixdbm, BIC is 2 loglik - df log(n) (larger is better; stats::BIC(fit) gives the same value with the opposite sign).

Value

An object of class "mallows": center (the central ranking), ocenter (the center as an ordering of the objects), lambda, se (its standard error), meandist (mean distance from the center), loglik, df, BIC, n, M, dist.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

Mallows, C.L. (1957). Non-null ranking models. I. Biometrika, 44, 114-130.

Fligner, M.A. and Verducci, J.S. (1986). Distance based ranking models. Journal of the Royal Statistical Society B, 48, 359-369.

Irurozki, E., Calvo, B. and Lozano, J.A. (2016). PerMallows: An R package for Mallows and generalized Mallows models. Journal of Statistical Software, 71(12), 1-30.

See Also

mixdbm, rmallows, mallowscenter, mallowsnorm

Examples

data(Irish)
## complete rankings only (rankings with ties are not supported yet)
X <- Irish$rankings[apply(Irish$rankings, 1, function(r) all(sort(r) == 1:5)), ]
fit <- mallows(X, dist = "kendall")
fit
summary(fit)
mallows(X, dist = "cayley")


Median ranking with respect to a distance

Description

Finds the ranking R minimising \sum_i w_i d(r_i, R) over all permutations: it is the maximum likelihood estimate of the center of the Mallows model.

Usage

mallowscenter(
  X,
  dist = "kendall",
  weights = NULL,
  centermethod = c("auto", "exhaustive", "local", "bb")
)

Arguments

X

A n by M matrix of complete rankings.

dist

The distance (see rankdist).

weights

Optional non-negative weights (default: all equal to 1).

centermethod

"auto" (default), "exhaustive", "local" or "bb" (see Details).

Details

Exact methods: weighted Borda count ("spearmansq"), assignment problem solved with the Hungarian algorithm ("footrule", "hamming"), Emond and Mason (2002) branch-and-bound of consrank (Kendall, used by "auto" when M > 8), exhaustive search ("auto": Kendall with M <= 8, the other distances with M <= 7). Otherwise a local search (swaps and moves of one object) from several starting points, which may stop at a local optimum.

Value

The median ranking (vector named after the objects).

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

Emond, E.J. and Mason, D.W. (2002). A new rank correlation coefficient with application to the consensus ranking problem. Journal of Multi-Criteria Decision Analysis, 11, 17-28.

See Also

mallows, consrank

Examples

data(Irish)
## complete rankings only (rankings with ties are not supported yet)
X <- Irish$rankings[apply(Irish$rankings, 1, function(r) all(sort(r) == 1:5)), ]
mallowscenter(X, dist = "kendall")
mallowscenter(X, dist = "footrule")


Normalising constant, moments and precision of the Mallows model

Description

For the Mallows (distance-based) model P(r) = C(\lambda) \exp\{-\lambda d(r, R)\}, mallowsnorm computes \psi(\lambda) = 1/C(\lambda), mallowsexpect the expected distance from the center (and its variance) and mallowslambda the maximum likelihood estimate of \lambda given the mean distance of the data from the center.

Usage

mallowsnorm(lambda, M, dist = "kendall", log = TRUE)

mallowsexpect(lambda, M, dist = "kendall", var = FALSE)

mallowslambda(meandist, M, dist = "kendall", lambdamax = 50)

Arguments

lambda

Precision (dispersion) parameter(s), \lambda \ge 0.

M

Number of objects.

dist

The distance (see rankdist).

log

If TRUE (default) \log\psi(\lambda).

var

If TRUE the variance of the distance is returned too.

meandist

Mean (possibly weighted) distance of the rankings from the center.

lambdamax

Upper bound for \lambda.

Details

By right-invariance the constant does not depend on the center. For Kendall and Cayley closed forms are used (any M); for the other distances the exact distribution of distfreq. The MLE of \lambda solves E_\lambda[d] = \bar d.

Value

mallowsnorm: \log\psi or \psi. mallowsexpect: the expectation (a matrix with expectation and variance if var = TRUE). mallowslambda: the estimate(s).

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

Mallows, C.L. (1957). Non-null ranking models. I. Biometrika, 44, 114-130.

Fligner, M.A. and Verducci, J.S. (1986). Distance based ranking models. Journal of the Royal Statistical Society B, 48, 359-369.

See Also

mallows, distfreq

Examples

mallowsnorm(0.5, M = 10, dist = "kendall")
mallowsexpect(c(0, 0.5, 1), M = 10, dist = "cayley", var = TRUE)
mallowslambda(10, M = 10, dist = "kendall")


Marginal distribution of the positions of the objects

Description

Computes the marginal matrix of a set of rankings (Marden, 1995, Section 2.3): for each object and each position, the number (and the proportion) of judges who put the object in that position, together with the mean rank of each object. Use plot to display it as a bubble plot.

Usage

marginals(X, wk = NULL)

Arguments

X

A n by m data matrix (or data frame), in which there are n judges and m objects to be judged. Each row is a ranking of the objects, which are represented by the columns; ties are allowed, and so are missing values (NA or NaN) for objects not ranked by a judge (e.g. top-k partial rankings), which are treated as tied in the last position.

wk

Optional vector of n non-negative weights (e.g. the frequencies of the distinct rankings in the rows of X). Default NULL: every judge has weight 1.

Details

The ranks are read as an order: the actual values do not matter, so c(1, 1, 3), c(1, 1, 2) and c(2, 2, 7) are the same ranking. Objects tied in a bucket that occupies the positions p, ..., q share these positions: the judge contributes 1/(q - p + 1) to each of them (the average over the random orderings of the tied objects). Hence every row and every column of the matrix of counts sums to the number (or the total weight) of the judges, and the mean rank of an object is its mean rank with ties (the midrank of its bucket). Objects not ranked by a judge form the last bucket of that judge's ranking. For complete rankings without ties this is the marginal matrix of Marden (1995).

Value

An object of class marginals, a list with:

counts the m by m matrix of counts (objects in rows, positions in columns)
prop the matrix of proportions (counts divided by nj)
meanrank the mean rank of each object
nj the number of judges (the sum of the weights)
ties TRUE if some rankings have ties or missing values
items the names of the objects

Author(s)

Luca Coraggio luca.coraggio@unina.it

References

Marden, J.I. (1995). Analyzing and Modeling Rank Data. Chapman & Hall, London.

See Also

plot.marginals, pairmatrix

Examples

data(Univranks)
mg <- marginals(Univranks$rankings)
mg
plot(mg)
# top-2 partial rankings (unranked objects coded as NaN)
data(EVS)
plot(marginals(EVS$rankings))


Metric and non-metric multidimensional scaling

Description

Metric and non-metric multidimensional scaling of a dissimilarity matrix, with the same goodness-of-fit criteria, options and output as the function mdscale of MATLAB (Statistics and Machine Learning Toolbox). It can be used on its own (for instance on a matrix of Kemeny distances between rankings) and as the MDS engine of kunfolding.

Usage

mdscale(
  D,
  p = 2,
  criterion = c("sstress", "stress", "metricstress", "metricsstress", "sammon", "strain"),
  weights = NULL,
  start = "cmdscale",
  replicates = 1,
  ties = c("primary", "secondary"),
  control = mdscalecontrol(...),
  ...
)

Arguments

D

the dissimilarities: a symmetric N by N matrix with zero diagonal and non-negative entries, an object of class dist, or a vector with the N(N-1)/2 elements of the upper triangle in the order of dist (the same order as the MATLAB function pdist). NA entries are missing values and are ignored. A symmetric matrix with ones along the diagonal and all other elements smaller than one is treated as a similarity matrix S and transformed into the dissimilarities sqrt(1 - S).

p

the number of dimensions of the solution. Default p = 2. It is ignored when start is a matrix or an array.

criterion

the goodness-of-fit criterion to minimise, which also sets the kind of scaling. Non-metric scaling: "sstress" (default; squared stress, normalised by the sum of fourth powers of the distances) or "stress" (Kruskal's stress-1, normalised by the sum of squared distances; the default of MATLAB, and the kind of criterion minimised by smacof). Metric scaling: "metricstress" (stress normalised by the sum of squared dissimilarities), "metricsstress" (squared stress normalised by the sum of fourth powers of the dissimilarities), "sammon" (Sammon's nonlinear mapping; the dissimilarities must be strictly positive) or "strain" (the criterion of classical scaling). See Details.

weights

optional non-negative weights for the dissimilarities, in the same form as D. Pairs with zero weight are ignored. The diagonal is ignored.

start

the starting configuration: "cmdscale" (default, the classical scaling solution; not allowed with missing dissimilarities or zero weights), "random" (independent normal coordinates, scaled so that the expected squared distance equals the mean squared dissimilarity), an N by p matrix, or an N by p by R array of R starting configurations.

replicates

the number of times the scaling is repeated, each time with a new starting configuration; the solution with the lowest criterion is returned. Default 1. With start = "cmdscale" all the replicates start from the same configuration; with an array it is the third dimension of the array.

ties

the treatment of tied dissimilarities in non-metric scaling: "primary" (default, as in MATLAB: tied dissimilarities may get different disparities) or "secondary" (tied dissimilarities get the same disparity). Ignored by the metric criteria.

control

a list of options of the algorithm, as returned by mdscalecontrol: maximum number of iterations, tolerances and display.

...

arguments passed to mdscalecontrol.

Details

Let d_ij be the Euclidean distances between the points of the configuration, D_ij the dissimilarities, w_ij the weights, and dh_ij the disparities, i.e. the weighted least squares monotone (non-decreasing) regression of the distances on the order of the dissimilarities. All sums are over the pairs i < j with non-missing dissimilarity and positive weight. The criteria are

stress sqrt( sum w (dh - d)^2 / sum w d^2 )
sstress sqrt( sum w (dh^2 - d^2)^2 / sum w d^4 )
metricstress sqrt( sum w (D - d)^2 / sum w D^2 )
metricsstress sqrt( sum w (D^2 - d^2)^2 / sum w D^4 )
sammon sum w (D - d)^2 / D / sum w D
strain sqrt( sum over all i, j of v_ij (b_ij - y_i'y_j)^2 )

where, for "strain", b_ij = -D_ij^2/2, v_ij = w_ij with v_ii = 1, and the points y_i are centred at their mean weighted by the row sums of the weights. Without weights the minimum of the strain is the classical scaling solution (cmdscale). For "sstress" the disparities are, as in MATLAB, the monotone regression of the distances (not of the squared distances).

The criterion is minimised as a function of the configuration only (for the non-metric criteria the disparities are recomputed at every evaluation) by a limited-memory BFGS method with a line search for the strong Wolfe conditions, written in C++. The iterations stop when the criterion is smaller than tolfun, or its relative change over the last window iterations is smaller than tolfun, or the norm of the gradient is smaller than tolfun, or the norm of the step is smaller than tolx, or after maxiter iterations (with a warning). These are the stopping rules and the default values of MATLAB, except that MATLAB measures the relative change over one iteration (window = 1); the default window = 10 avoids stopping at an iteration that happens to make little progress. The algorithm is not the one of MATLAB, so the two functions can stop at different local minima; from the same starting configuration and with small tolerances they usually reach the same solution. Since the criteria can have several local minima, replicates with start = "random" is recommended.

The returned configuration is centred at the origin and rotated to its principal axes, with the sign of each axis chosen so that its largest absolute coordinate is positive. For the non-metric criteria, which do not depend on the scale of the configuration, the configuration is scaled so that the weighted sum of squared distances equals the weighted sum of squared dissimilarities.

Value

An object of the class mdscale, a list with:

conf the N by p configuration
stress the value of the criterion at the configuration
disparities the N by N matrix of disparities (non-metric criteria) or the dissimilarities (metric criteria); NA for the ignored pairs
dissimilarities the N by N matrix of dissimilarities
distances the N by N matrix of distances between the points of conf
weights the N by N matrix of weights (NULL if not given)
criterion the criterion
ties the treatment of ties (non-metric criteria)
iterations the number of iterations of the best replicate
converged TRUE if a stopping rule other than the iteration limit was met
message the stopping rule that ended the iterations
allstress the value of the criterion for each replicate
call the matched call

Author(s)

Antonio D'Ambrosio antdambr@unina.it, Luca Coraggio luca.coraggio@unina.it

References

Kruskal, J.B. (1964). Nonmetric multidimensional scaling: a numerical method. Psychometrika, 29, 115-129.

Takane, Y., Young, F.W., and de Leeuw, J. (1977). Nonmetric individual differences multidimensional scaling: an alternating least squares method with optimal scaling features. Psychometrika, 42, 7-67.

Sammon, J.W. (1969). A nonlinear mapping for data structure analysis. IEEE Transactions on Computers, 18, 401-409.

Torgerson, W.S. (1958). Theory and Methods of Scaling. Wiley, New York.

Borg, I., and Groenen, P.J.F. (2005). Modern Multidimensional Scaling: Theory and Applications (2nd ed.). Springer, New York.

Nocedal, J., and Wright, S.J. (2006). Numerical Optimization (2nd ed.). Springer, New York.

See Also

mdscalecontrol, plot.mdscale, kunfolding, cmdscale

Examples

data(Univranks)
# Kemeny distances between the rankings of the judges
DK <- ConsRank::kemenyd(Univranks$rankings)
# non-metric scaling
out <- mdscale(DK, p = 2)
out
plot(out)
plot(out, type = "shepard")
# metric scaling
out2 <- mdscale(DK, criterion = "metricstress")
out2$stress


Options of the algorithm of mdscale

Description

Options that control the iterative algorithm of mdscale. Names and default values are those of the options of the MATLAB function mdscale.

Usage

mdscalecontrol(
  maxiter = 200,
  tolfun = 1e-04,
  tolx = 1e-04,
  display = c("off", "final", "iter"),
  window = 10
)

Arguments

maxiter

the maximum number of iterations. Default 200.

tolfun

the termination tolerance for the criterion, for its relative change and for the norm of its gradient. Default 1e-4.

tolx

the termination tolerance for the norm of the step. Default 1e-4.

display

the amount of output printed: "off" (default), "final" (iterations and final criterion of each replicate) or "iter" (one line per iteration).

window

the number of iterations over which the relative change of the criterion is measured: the iterations stop when the criterion has decreased by less than tolfun (in relative terms) over the last window iterations. Default 10. With window = 1 the rule is the one of MATLAB (relative change over one iteration); a longer window avoids stopping at an iteration that happens to make little progress far from the minimum.

Value

A list with the options.

Author(s)

Antonio D'Ambrosio antdambr@unina.it, Luca Coraggio luca.coraggio@unina.it

See Also

mdscale

Examples

ctl <- mdscalecontrol(maxiter = 500, tolfun = 1e-6)


Utility function

Description

Utility function to use to set the control arguments of kunfolding

Usage

mdscontrol(
  model = "ordinal",
  init = "torgerson",
  transf = "primary",
  userinit = NULL,
  w = NULL,
  minstress = 1e-05,
  itermax = 500,
  printscr = TRUE,
  spline.degree = 2,
  spline.intKnots = 2,
  relax = FALSE,
  modulus = 1,
  engine = "smacof",
  criterion = NULL,
  nrep = 1
)

Arguments

model

Specifies MDS model. One among "ordnal (default)" or "metric"

init

Initial configuration. One among "torgerson" (degault), "random" or "user"

transf

The transformation. One among "primary" (default), "secondary","tertiary","spline","ratio","interval","none"

userinit

The user initial configuration if "init" has been set as "user"

w

The set of weigths. Default: NULL

minstress

the minimum stress (for stress method). Default 1e-5

itermax

Maximum number if iterations. Default 500

printscr

Display the messages and the summary of the model. Default TRUE

spline.degree

Degree of spline transformation. Default 2

spline.intKnots

Interior knots. default 2

relax

Relax the solution. Default FALSE

modulus

Modulus. Default 1

engine

The MDS engine: "smacof" (default, the function smacofSym of the package smacof) or "mdscale" (the function mdscale of this package, which minimises the criteria of the MATLAB function mdscale). With both engines transf = "primary", "secondary" or "tertiary" gives an ordinal MDS whatever model is. With "mdscale", transf = "primary" or "secondary" minimises the squared stress (criterion = "sstress", the default of mdscale) with that approach to ties, and transf = "ratio" or "none" minimises the metric squared stress (criterion = "metricsstress"); the other transformations are not available. minstress and itermax are passed to mdscalecontrol as tolfun (and tolx) and maxiter.

criterion

Only for engine = "mdscale": the criterion of mdscale ("stress", "sstress", "metricstress", "metricsstress", "sammon" or "strain"). Default NULL: the criterion implied by model and transf, as described above.

nrep

Only for engine = "mdscale": the number of replicates (see the argument replicates of mdscale). Default 1.

Value

A list containing all the control parameters

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

kunfolding, mdscale


Mixtures of distance-based (Mallows) models for rankings

Description

Fits the mixture of distance-based models of Murphy and Martin (2003),

f(r) = \sum_{g=1}^G p_g C(\lambda_g) \exp\{-\lambda_g d(r, R_g)\} \; (+ \, p_0 / M!)

by the EM algorithm from multiple random starts.

Usage

mixdbm(
  X,
  G,
  dist = "kendall",
  lambda = c("free", "equal"),
  noise = FALSE,
  startfrom = NULL,
  control = mixdbmcontrol(...),
  ...
)

Arguments

X

A n by M matrix of complete rankings (rank of object j in column j).

G

Number of (non-uniform) components. G = 0 with noise = TRUE gives the uniform model ("0+N" in the paper).

dist

The distance: "kendall", "cayley", "hamming", "ulam", "footrule", "spearman" (as in the paper) or "spearmansq" (see rankdist).

lambda

Constraint on the precisions: "free" or "equal".

noise

If TRUE a uniform (\lambda = 0) noise component is added.

startfrom

Optional mixdbm fit with G - 1 components (same distance and noise option): three extra starts are made of its solution plus a new component.

control

A list of options, see mixdbmcontrol.

...

Options passed to mixdbmcontrol bypassing control.

Details

Data are collapsed into distinct rankings with frequencies. The M-step for the centers is exact for Kendall (exhaustive search, or the branch-and-bound of consrank when M > 8), footrule, Hamming and squared Spearman, and for the other distances when M <= 7; otherwise a local search is used (generalised EM). The normalising constants are exact. BIC = 2 loglik - df log(n) and ICL = BIC + 2 sum z log z as in the paper (larger is better). Components are ordered by decreasing proportion; the noise component is the last one.

A component is degenerate when its precision reaches lambdamax and its expected size is below minsize (see mixdbmcontrol): it describes a few copies of one ranking, not a group of similar rankings, and the likelihood increases without limit towards lambda = Inf. Such solutions can win by BIC and ICL, so the best start without degenerate components is kept; if every start is degenerate the best one is returned with a warning.

Value

An object of class "mixdbm": centers (G by M matrix of central rankings), ocenters (centers as orderings of the objects), lambda (precisions), p (mixing proportions, noise last), z (n by (G + noise) posterior membership probabilities), cluster (crisp partition: column of z with the highest probability), loglik, df, BIC, ICL, n, M, G, noise, dist, lambdamodel, model, iter, converged, lltrace (log-likelihood at each EM iteration of the best start), loglikstarts (final log-likelihood of every start), degstarts (logical: was each start degenerate?), degenerate (names of the degenerate components of the returned solution: empty unless every start was degenerate), control.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

Murphy, T.B. and Martin, D. (2003). Mixtures of distance-based models for ranking data. Computational Statistics & Data Analysis, 41, 645-655.

Celeux, G. and Diebolt, J. (1985). The SEM algorithm: a probabilistic teacher algorithm derived from the EM algorithm for the mixture problem. Computational Statistics Quarterly, 2, 73-82.

See Also

mixdbmcontrol, mixdbmselect, rmixdbm, mallows, cca

Examples


data(Irish)
## complete rankings only (rankings with ties are not supported yet)
X <- Irish$rankings[apply(Irish$rankings, 1, function(r) all(sort(r) == 1:5)), ]
set.seed(1)
fit <- mixdbm(X, G = 2, dist = "kendall", nstart = 5)
fit
summary(fit)



Control parameters for mixdbm

Description

Options of the EM algorithm of mixdbm and mixdbmselect.

Usage

mixdbmcontrol(
  nstart = 30,
  init = c("mixed", "partition", "centers", "sem"),
  semiter = 100,
  maxiter = 1000,
  tol = 1e-10,
  centerdf = 0,
  centermethod = c("auto", "exhaustive", "local", "bb"),
  lambdamax = 50,
  minsize = 5,
  verbose = FALSE
)

Arguments

nstart

Number of random starts (Murphy and Martin use 30).

init

Starting values: "mixed" (default, alternates "partition" and "centers"), "partition" (random soft partition of the data followed by an M-step), "centers" (centers drawn from the observed rankings) or "sem" (random partition, then semiter iterations of the stochastic EM of Celeux and Diebolt, 1985; the best visited parameters start the EM).

semiter

Number of SEM iterations per start when init = "sem".

maxiter

Maximum number of EM iterations per start.

tol

Relative tolerance on the log-likelihood for convergence.

centerdf

Degrees of freedom charged to each central ranking in BIC and ICL (default 0: centers are discrete and not counted; the paper does not state it).

centermethod

Method for the M-step of the centers (see mallowscenter).

lambdamax

Upper bound for the precisions.

minsize

A component is degenerate when its precision reaches lambdamax and its expected size n p_g is below minsize (default 5): it is concentrated on a few copies of one ranking and is a spurious maximum at the boundary (lambda = Inf) of the parameter space. The best non-degenerate start is kept (see mixdbm). minsize = 0 switches the check off.

verbose

If TRUE prints the log-likelihood reached by each start.

Value

A list with the options.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbm


Model selection for mixtures of distance-based models

Description

Fits mixdbm over a grid of distances, precision constraints, noise options and numbers of components, and compares the models by BIC and ICL.

Usage

mixdbmselect(
  X,
  G = 1:5,
  dist = c("kendall", "spearman", "cayley"),
  lambda = c("free", "equal"),
  noise = c(FALSE, TRUE),
  nested = TRUE,
  trace = TRUE,
  control = mixdbmcontrol(...),
  ...
)

Arguments

X

A n by M matrix of complete rankings.

G

Vector of numbers of components (0 is used only with noise).

dist

Vector of distances (see rankdist).

lambda

Vector of precision constraints ("free", "equal").

noise

Vector of noise options (FALSE, TRUE).

nested

If TRUE each fit with G components also starts from the best fit with G - 1 components plus one new component.

trace

If TRUE (default) prints one line per fitted model.

control, ...

Options, see mixdbmcontrol.

Value

An object of class "mixdbmselect": table (one row per model with loglik, df, BIC, ICL and degenerate, TRUE when every start gave a degenerate solution, see mixdbm), fits (all the fitted models, named as in the table), bestBIC, bestICL (the best models among the non-degenerate ones).

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

Murphy, T.B. and Martin, D. (2003). Mixtures of distance-based models for ranking data. Computational Statistics & Data Analysis, 41, 645-655.

See Also

mixdbm

Examples


data(Irish)
## complete rankings only (rankings with ties are not supported yet)
X <- Irish$rankings[apply(Irish$rankings, 1, function(r) all(sort(r) == 1:5)), ]
set.seed(1)
sel <- mixdbmselect(X, G = 1:3, dist = c("kendall", "cayley"),
                    lambda = "free", noise = FALSE, nstart = 5)
sel



Path of a terminal node

Description

Given an object of the class "ranktree", it visualize the path leading to the terminal node

Usage

nodepath(termnode, Tree)

Arguments

termnode

The terminal node of which the path has to be extracted

Tree

An object of the class "ranktree"

Value

The path leading to the terminal node

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

ranktree, treepaths, getsubtree

Examples


data(Irish)
#build the tree with default options
tree <- ranktree(Irish$rankings,Irish$predictors)
#get information about all the paths leading to terminal nodes
paths <- treepaths(tree)
#see the path for terminal node number 8
nodepath(termnode=8,tree)

 

Hierarchical clustering of the objects

Description

Clusters the objects of a set of rankings (Marden, 1995, Example 2.18): the distance between two objects is the mean squared difference between the ranks the judges give them, so objects are close when the judges assign them similar ranks. Use plot to draw the dendrogram.

Usage

objclust(X, wk = NULL, method = "complete")

Arguments

X

A n by m data matrix (or data frame), in which there are n judges and m objects to be judged. Each row is a ranking of the objects, which are represented by the columns; ties are allowed, and so are missing values (NA or NaN) for objects not ranked by a judge (e.g. top-k partial rankings), which are treated as tied in the last position.

wk

Optional vector of n non-negative weights (e.g. the frequencies of the distinct rankings in the rows of X). Default NULL: every judge has weight 1.

method

The agglomeration method of hclust. Default "complete" (complete linkage, as in Marden, 1995).

Details

The distance between objects k and l is \sum w (y_k - y_l)^2 / \sum w, where y_k is the rank of object k given by a judge (with ties, the midrank of its bucket) and w the weight of the judge.

Value

An object of class objclust, a list with:

dist the distances between the objects (an object of class dist)
hclust the hierarchical clustering (an object of class hclust)
nj the number of judges (the sum of the weights)
items the names of the objects

Use cutree on the component hclust to get the groups of objects.

Author(s)

Luca Coraggio luca.coraggio@unina.it

References

Marden, J.I. (1995). Analyzing and Modeling Rank Data. Chapman & Hall, London.

See Also

plot.objclust, rankproj

Examples

data(sports, package = "ConsRank")
oc <- objclust(sports)
oc
plot(oc)
stats::cutree(oc$hclust, k = 3)


Matrix of pairwise preferences

Description

Computes the pairs matrix of a set of rankings (Marden, 1995, Section 2.4): for each ordered pair of objects (a, b), the number of judges who prefer a to b, and the number of judges who tie them. Use plot to display it as a heatmap.

Usage

pairmatrix(X, wk = NULL)

Arguments

X

A n by m data matrix (or data frame), in which there are n judges and m objects to be judged. Each row is a ranking of the objects, which are represented by the columns; ties are allowed, and so are missing values (NA or NaN) for objects not ranked by a judge (e.g. top-k partial rankings), which are treated as tied in the last position.

wk

Optional vector of n non-negative weights (e.g. the frequencies of the distinct rankings in the rows of X). Default NULL: every judge has weight 1.

Details

A smaller rank means a preferred object. The counts are kept separate: wins[a, b] judges prefer a to b, wins[b, a] prefer b to a, and ties[a, b] tie them, so wins[a, b] + wins[b, a] + ties[a, b] is the number (total weight) of the judges. An object ranked by a judge is preferred to the objects not ranked by that judge, and two unranked objects are tied.

Three matrices of proportions are returned. In prop each tie counts as half a preference for each object, so prop[a, b] + prop[b, a] = 1 and, for complete rankings without ties, prop is the pairs matrix of Marden (1995); strict contains the proportions of strict preferences (ties excluded from the numerator) and tieprop the proportions of ties. The score of each object is the mean of its row of prop, i.e. the normalised Borda score: the proportion of the other objects it beats, ties counting one half. The combined input matrix of Emond and Mason (2002), used by consrank, is wins + ties - t(wins) (with zero diagonal).

Value

An object of class pairmatrix, a list with:

wins the m by m matrix of the number of judges preferring the row object to the column object
ties the m by m symmetric matrix of the number of judges tying the two objects
prop the proportions of preferences, ties counting one half (NA on the diagonal)
strict the proportions of strict preferences (NA on the diagonal)
tieprop the proportions of ties (NA on the diagonal)
score the normalised Borda score of each object (mean of its row of prop)
nj the number of judges (the sum of the weights)
items the names of the objects

Author(s)

Luca Coraggio luca.coraggio@unina.it

References

Marden, J.I. (1995). Analyzing and Modeling Rank Data. Chapman & Hall, London.

Emond, E.J., and Mason, D.W. (2002). A new rank correlation coefficient with application to the consensus ranking problem. Journal of Multi-Criteria Decision Analysis, 11, 17-28.

See Also

plot.pairmatrix, marginals

Examples

data(Univranks)
pm <- pairmatrix(Univranks$rankings)
pm
plot(pm)
plot(pm, type = "ties")


Plot a multidimensional scaling of the judges

Description

Plots the configuration of the judges: each distinct ranking is a symbol whose area is proportional to the number of judges giving it, optionally with a different symbol for each group of judges.

Usage

## S3 method for class 'judgemds'
plot(
  x,
  dims = c(1, 2),
  groups = NULL,
  labels = FALSE,
  maxcex = 3,
  main = NULL,
  xlab = NULL,
  ylab = NULL,
  ...
)

Arguments

x

An object of class judgemds, as returned by judgemds.

dims

The two dimensions to plot. Default c(1, 2).

groups

Optional factor (or vector) with one value for each row of the data given to judgemds (e.g. the leaves of a tree, the clusters of a mixture, or a covariate): the judges are plotted with a different symbol for each group, and a legend is added.

labels

If TRUE, each distinct ranking is labelled with its order of the objects (ties in brackets). Default FALSE.

maxcex

Size (cex) of the symbol of the most frequent ranking. Default 3.

main

Title of the plot. Default: none.

xlab, ylab

Labels of the axes. Defaults: "Dimension 1" and "Dimension 2" (or the dimensions chosen).

...

Other arguments passed to xyplot.

Value

An object of class trellis (printed, so the plot is drawn, when not assigned).

See Also

judgemds

Examples

data(EVS)
plot(judgemds(EVS$rankings), labels = TRUE)


Plot Kemeny equivalent augmented unfolding solution

Description

Plot the Kemeny equivalent augmented unfolding coming from kunfolding

Usage

## S3 method for class 'kunfolding'
plot(
  x,
  labs = NULL,
  labsrow = NULL,
  main = NULL,
  cols = NULL,
  cexind = 1,
  cexitems = 1,
  pchcol = 15,
  bw = FALSE,
  ...
)

Arguments

x

An object of the class "kunfolding"

labs

The labels of the items. Defalut is NULL. If not provided, a sequence "o1,...,on" is printed, with n=number of items

labsrow

The labels of the individuals. Defalut is NULL. If not provided, a sequence "1,...,m" is printed, with m=number of individuals

main

Main title of the plot. Default NULL

cols

Groups of the individuals, drawn with different colours (with bw = TRUE, different symbols): numeric codes, or a factor. Default is NULL (dark gray).

cexind

cex of the individuals. Default 1

cexitems

cex of the items. defaul 1

pchcol

pch parameter for items points. Default 15

bw

Logical. If TRUE, a black and white plot: the individuals are grey points (without numbers, unless labsrow is given), the items black symbols with their labels above them. With cols (numeric groups of individuals) the groups are drawn with different symbols, with a legend. Default FALSE (the plot with colours).

...

System reserved (No specific usage)

Value

the plot of unfolding solution

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

kunfolding, augmatrix

Examples

data("breakfast", package="smacof")
unfout <- kunfolding(breakfast)
itemsl <- colnames(breakfast)
plot(unfout,labs=itemsl,cexitems=0.8)
plot(unfout,labs=itemsl,cexitems=0.8,bw=TRUE)


Plot a marginal matrix

Description

Bubble plot of the marginal matrix of a set of rankings: the objects are in the rows and the positions in the columns, and the area of each circle is proportional to the proportion of judges who put the object in that position. The mean rank of each object can be marked on its row.

Usage

## S3 method for class 'marginals'
plot(
  x,
  order = c("meanrank", "none"),
  meanrank = TRUE,
  values = FALSE,
  maxradius = 0.45,
  main = NULL,
  xlab = "Position",
  ylab = NULL,
  ...
)

Arguments

x

An object of class marginals, as returned by marginals.

order

The order of the objects (rows, from the top): "meanrank" (default, from the smallest mean rank) or "none" (the order of the columns of the data).

meanrank

If TRUE (default), the mean rank of each object is marked with a filled diamond on its row.

values

If TRUE, the proportions (in percent) are written in the circles. Default FALSE.

maxradius

Radius of the circle of the largest proportion, as a fraction of the distance between two positions. Default 0.45.

main

Title of the plot. Default: none.

xlab, ylab

Labels of the axes. Defaults: "Position" and none.

...

Other arguments passed to xyplot.

Value

An object of class trellis (printed, so the plot is drawn, when not assigned).

Author(s)

Luca Coraggio luca.coraggio@unina.it

See Also

marginals

Examples

data(Univranks)
plot(marginals(Univranks$rankings), values = TRUE)


Plot method for mdscale

Description

Plots the configuration of an mdscale solution, or its Shepard diagram.

Usage

## S3 method for class 'mdscale'
plot(
  x,
  type = c("configuration", "shepard"),
  dims = c(1, 2),
  labels = NULL,
  col = "black",
  cex = 0.8,
  main = NULL,
  ...
)

Arguments

x

an object of the class mdscale, as returned by mdscale.

type

"configuration" (default) for the points in two of the dimensions, or "shepard" for the Shepard diagram: the distances (points) and, for the non-metric criteria, the disparities (line) against the dissimilarities.

dims

the two dimensions to plot. Default c(1, 2).

labels

the labels of the points. Default: the names of the rows of the configuration, or the numbers of the points if there are no names. Use labels = FALSE to plot the points without labels.

col

the colour of the points (configuration) or of the distances (Shepard diagram). Default "black".

cex

the size of the labels and of the points. Default 0.8.

main

the title of the plot. Default: none.

...

other graphical parameters passed to plot.

Details

In the configuration plot the two axes have the same scale, so that the distances in the plot are the distances of the solution.

Value

No return value, called for its side effect (a plot).

Author(s)

Antonio D'Ambrosio antdambr@unina.it, Luca Coraggio luca.coraggio@unina.it

See Also

mdscale

Examples

data(Univranks)
out <- mdscale(ConsRank::kemenyd(Univranks$rankings))
plot(out)
plot(out, type = "shepard")


Plot a clustering of the objects

Description

Draws the dendrogram of the hierarchical clustering of the objects.

Usage

## S3 method for class 'objclust'
plot(x, k = NULL, main = "", ylab = "Mean squared rank difference", ...)

Arguments

x

An object of class objclust, as returned by objclust.

k

Optional number of groups: if given, the groups are enclosed in rectangles (see rect.hclust).

main

Title of the plot. Default: none.

ylab

Label of the vertical axis. Default "Mean squared rank difference".

...

Other arguments passed to plot for hclust objects.

Value

x, invisibly.

See Also

objclust

Examples

data(sports, package = "ConsRank")
plot(objclust(sports), k = 3)


Plot a matrix of pairwise preferences

Description

Heatmap, in grey levels, of a matrix of pairwise preferences: the cell in row a and column b is the proportion of judges preferring a to b (darker: larger).

Usage

## S3 method for class 'pairmatrix'
plot(
  x,
  type = c("half", "strict", "ties"),
  order = c("score", "none"),
  values = TRUE,
  digits = 2,
  main = NULL,
  xlab = NULL,
  ylab = NULL,
  ...
)

Arguments

x

An object of class pairmatrix, as returned by pairmatrix.

type

The proportions displayed: "half" (default; ties count one half, so the cells (a, b) and (b, a) sum to one), "strict" (strict preferences only) or "ties" (proportion of ties, a symmetric matrix).

order

The order of the objects: "score" (default, from the largest normalised Borda score, so the darker cells are above the diagonal) or "none" (the order of the columns of the data).

values

If TRUE (default), the proportions are written in the cells.

digits

Number of decimal digits of the values. Default 2.

main

Title of the plot. Default: none.

xlab, ylab

Labels of the axes. Defaults: none.

...

Other arguments passed to levelplot.

Value

An object of class trellis (printed, so the plot is drawn, when not assigned).

Author(s)

Luca Coraggio luca.coraggio@unina.it

See Also

pairmatrix

Examples

data(Univranks)
plot(pairmatrix(Univranks$rankings))


Plot a projection of rankings

Description

Plots the projection of a set of rankings on two axes of the permutation polytope (a projected "polytope-o-gram", Marden, 1995, Section 2.2): each distinct ranking is a symbol whose area is proportional to the number of judges giving it, the poles of the objects are arrows from the center, and the unit circle (where the permutations lie when the projection is exact) is drawn as a reference.

Usage

## S3 method for class 'rankproj'
plot(
  x,
  dims = c(1, 2),
  groups = NULL,
  labels = FALSE,
  maxcex = 3,
  main = NULL,
  xlab = NULL,
  ylab = NULL,
  labpos = NULL,
  laboffset = NULL,
  ...
)

Arguments

x

An object of class rankproj, as returned by rankproj.

dims

The two dimensions to plot. Default c(1, 2).

groups

Optional factor (or vector) with one value for each row of the data given to rankproj (e.g. the leaves of a tree, the clusters of a mixture, or a covariate): the judges are plotted with a different symbol for each group, and a legend is added.

labels

If TRUE, each distinct ranking is labelled with its order of the objects (ties in brackets). Default FALSE; useful with few distinct rankings.

maxcex

Size (cex) of the symbol of the most frequent ranking. Default 3.

main

Title of the plot. Default: none.

xlab, ylab

Labels of the axes. Default: the dimension and its proportion of the sum of the eigenvalues.

labpos

Position of the names of the objects with respect to the tips of their poles, coded as in text: 1 below, 2 left, 3 above, 4 right. A single value for all the objects, one value for each object, or a named vector for some objects only (e.g. c(Tennis = 1)). Default NULL: left of the tip for the poles pointing left, right of it for the others.

laboffset

Shifts of the names of the objects, to separate overlapping names: a named list of vectors c(dx, dy) in the units of the plot (the unit circle has radius 1), e.g. list(Tennis = c(0, -0.08)), or a matrix with two columns and one row for each object. Default NULL (no shift).

...

Other arguments passed to xyplot.

Value

An object of class trellis (printed, so the plot is drawn, when not assigned).

Author(s)

Luca Coraggio luca.coraggio@unina.it

See Also

rankproj

Examples

data(sports, package = "ConsRank")
plot(rankproj(sports))
# names of the objects moved by hand
plot(rankproj(sports), labpos = c(Tennis = 2, Cycling = 3),
     laboffset = list(Swimming = c(0, -0.06)))


Plot tree-based structure or pruning sequence of ranktree

Description

Plot the tree coming from the ranktree or the pruning sequence of the ranktree

Usage

## S3 method for class 'ranktree'
plot(
  x,
  plot.type = "tree",
  dispclass = FALSE,
  valtree = NULL,
  taos = TRUE,
  style = c("classic", "compact"),
  cex = 1,
  ...
)

Arguments

x

An object of the class "ranktree"

plot.type

One among "tree" or "pruningseq"

dispclass

Display the median ranking above terminal nodes. Default option: FALSE

valtree

If plot.type="pruningseq", it shows the Tau_x rank correlation coefficient or the error along the pruning sequence on the training set. If valtree is the output of the function validatetree, it shows either the Tau_x rank correlation coefficient or the error along the pruning sequence of also the decision tree (validated by wither test set or cross-validation)

taos

If plot.type="pruningseq", it plots the Tau_x rank correlation coefficient along the pruning sequence. If taos=FALSE, it plots the error.

style

If plot.type="tree", the drawing of the tree: "classic" (default, the drawing used so far) or "compact", a black and white drawing from left to right (see details).

cex

Only for style = "compact": a factor that enlarges (> 1) or reduces (< 1) all the text of the drawing. Default 1.

...

System reserved (No specific usage)

Details

With style = "compact" the tree grows from left to right, in black and white: each internal node is a dot, the condition of each branch is written on it (for a nominal predictor the categories present in the child node, or the categories excluded if they are fewer; for a numeric predictor the bound), and the terminal nodes are aligned on the right, each with its class (as an ordering: objects tied in a bucket in parentheses; with topk in ranktreecontrol only the first k objects), its size and its Tau_x (on the observed pairs with unranked = "unknown"). The classes are always displayed, so dispclass is ignored. The labels of the branches are wrapped to fit their length: for a large tree, enlarge the plotting region or reduce cex.

For a tree built with model = "mallows" (see ranktree) the terminal nodes display the modal ranking of the Mallows model (dispclass=TRUE), and the pruning sequence shows the mean deviance per ranking on the training set and, if valtree is given, on the test set or in cross-validation, with bars of plus/minus one standard error and the subtree chosen by the 1-SE rule (filled point); taos is ignored.

Value

the plot of either the tree or the pruning sequence

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

ranktree, validatetree

Examples

data("Univranks")
tree <- ranktree(Univranks$rankings,Univranks$predictors,num=50)
plot(tree,dispclass=TRUE)
plot(tree,style="compact")


data(EVS)
EVS$rankings[is.na(EVS$rankings)] <- 3
set.seed(654)
training=sample(1911,1434)
tree <- ranktree(EVS$rankings[training,],EVS$predictors[training,],decrmin=0.001,num=50)
plot(tree,dispclass=TRUE)
#test set validation
vtreetest <- validatetree(tree,testX=EVS$predictors[-training,],EVS$rankings[-training,]) 
dtree <- getsubtree(tree,vtreetest$best_tau)
plot(dtree,dispclass=TRUE)
#see the global weigthted tau_X rank correlation coefficients
plot(tree,plot.type="pruningseq",valtree=vtreetest)
#see the error rates
plot(tree,plot.type="pruningseq",valtree=vtreetest, taos=FALSE)



Cluster membership of new rankings from a mixdbm fit

Description

Posterior membership probabilities of new rankings under a fitted mixture of distance-based models.

Usage

## S3 method for class 'mixdbm'
predict(object, newdata, ...)

Arguments

object

An object of class "mixdbm".

newdata

A matrix of complete rankings of the same objects.

...

Not used.

Value

A list with z (matrix of posterior probabilities, one column per component, noise last) and cluster (column of z with the highest probability).

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbm

Examples

set.seed(1)
X <- rmixdbm(300, centers = rbind(1:5, 5:1), lambda = c(1, 1),
             p = c(0.5, 0.5), dist = "kendall")
fit <- mixdbm(X, G = 2, dist = "kendall", nstart = 3)
predict(fit, rbind(1:5, c(5, 4, 3, 1, 2)))

Predict the median rankings for new observations

Description

Predict the median rankings in a tree-based structure built with ranktree for new observations

Usage

## S3 method for class 'ranktree'
predict(object, newx, ...)

Arguments

object

An object of the class "ranktree"

newx

A dataframe of the same nature of the predictor dataframe with which the tree has been built

...

System reserved (No specific usage)

Value

A list containing:

rankings the fit in terms of rankings
orderings the fit in terms of orderings
info dataframe containing the terminal nodes in which the new x fall down (column leafid: the node numbers, as in print, summary and nodepath), then the new x and the fit (in terms of rankings)

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

ranktree validatetree

Examples


data(EVS)
EVS$rankings[is.na(EVS$rankings)] <- 3
set.seed(654)
training=sample(1911,1434)
tree <- ranktree(EVS$rankings[training,],EVS$predictors[training,],decrmin=0.001,num=50)
#use the function predict ro predict rankings for new predictors
rankfit <- predict(tree,newx=EVS$predictors[-training,])
#fit in terms of rankings
rankfit$rankings
#fit in terms of orderings
rankfit$orderings
# information about the fit (terminal node, predictor and fit (in terms of rankings))
rankfit$info





S3 methods for cca

Description

Print methods for objects of class cca

Usage

## S3 method for class 'cca'
print(x, ...)

Arguments

x

An object of the class "cca"

...

not used

Value

print a brief summary of the CCA


Print a multidimensional scaling of the judges

Description

Print method for objects of class judgemds.

Usage

## S3 method for class 'judgemds'
print(x, ...)

Arguments

x

An object of class judgemds.

...

Not used.

Value

x, invisibly.


S3 methods for kunfolding

Description

Print methods for objects of class kunfolding

Usage

## S3 method for class 'kunfolding'
print(x, ...)

Arguments

x

An object of the class "kunfolding"

...

not used

Value

print a brief summary of the Kemeny equivalent augmented unfolding


Print method for mallows objects

Description

Prints the estimated center (as ranking and as ordering), the precision with its standard error, the mean distance and the log-likelihood.

Usage

## S3 method for class 'mallows'
print(x, digits = 4, ...)

Arguments

x

An object of class "mallows".

digits

Number of significant digits.

...

Not used.

Value

The object, invisibly.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mallows


Print a marginal matrix

Description

Print method for objects of class marginals.

Usage

## S3 method for class 'marginals'
print(x, digits = 3, ...)

Arguments

x

An object of class marginals.

digits

Number of decimal digits of the proportions. Default 3.

...

Not used.

Value

x, invisibly.


Print and summary methods for mdscale

Description

Print and summary methods for objects of the class mdscale.

Usage

## S3 method for class 'mdscale'
print(x, ...)

## S3 method for class 'mdscale'
summary(object, ...)

Arguments

x, object

an object of the class mdscale, as returned by mdscale.

...

not used.

Details

print shows the criterion, its value at the solution and the convergence; summary also shows the value of the criterion for each replicate and the first rows of the configuration.

Value

The object, invisibly.

Author(s)

Antonio D'Ambrosio antdambr@unina.it, Luca Coraggio luca.coraggio@unina.it

See Also

mdscale, plot.mdscale

Examples

data(Univranks)
out <- mdscale(ConsRank::kemenyd(Univranks$rankings))
print(out)
summary(out)


Print method for mixdbm objects

Description

Prints the cluster centers (as orderings and as rankings), precisions, mixing proportions, log-likelihood, BIC and ICL.

Usage

## S3 method for class 'mixdbm'
print(x, digits = 3, ...)

Arguments

x

An object of class "mixdbm".

digits

Number of significant digits.

...

Not used.

Value

The object, invisibly.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbm


Print method for mixdbmselect objects

Description

Prints the best models by BIC and by ICL.

Usage

## S3 method for class 'mixdbmselect'
print(x, top = 10, ...)

Arguments

x

An object of class "mixdbmselect".

top

Number of models shown for each criterion.

...

Not used.

Value

The object, invisibly.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbmselect


Print a clustering of the objects

Description

Print method for objects of class objclust.

Usage

## S3 method for class 'objclust'
print(x, digits = 3, ...)

Arguments

x

An object of class objclust.

digits

Number of decimal digits. Default 3.

...

Not used.

Value

x, invisibly.


Print a matrix of pairwise preferences

Description

Print method for objects of class pairmatrix.

Usage

## S3 method for class 'pairmatrix'
print(x, digits = 3, ...)

Arguments

x

An object of class pairmatrix.

digits

Number of decimal digits of the proportions. Default 3.

...

Not used.

Value

x, invisibly.


Print a projection of rankings

Description

Print method for objects of class rankproj.

Usage

## S3 method for class 'rankproj'
print(x, digits = 3, ...)

Arguments

x

An object of class rankproj.

digits

Number of decimal digits. Default 3.

...

Not used.

Value

x, invisibly.


S3 methods for ranktree

Description

Print methods for objects of class ranktree

Usage

## S3 method for class 'ranktree'
print(x, ...)

Arguments

x

An object of the class "ranktree"

...

not used

Value

print a brief summary of the prediction tree. For a tree built with model = "mallows" (see ranktree) the summary concerns the Mallows models of the leaves: log-likelihood, deviance, number of parameters, AIC and BIC

Examples


data("Univranks")
tree <- ranktree(Univranks$rankings,Univranks$predictors,num=50)
tree




Distances between complete rankings

Description

Computes distances between complete rankings (no ties) for several metrics on permutations. rankdist is the general function; kendalld, cayleyd, hammingd, ulamd, footruled and spearmand are shortcuts for a given metric.

Usage

rankdist(X, Y = NULL, dist = "kendall")

kendalld(X, Y = NULL)

cayleyd(X, Y = NULL)

hammingd(X, Y = NULL)

ulamd(X, Y = NULL)

footruled(X, Y = NULL)

spearmand(X, Y = NULL, squared = FALSE)

Arguments

X

A n by M matrix of complete rankings (rank of object j in column j, 1 = most preferred), or a single ranking (vector).

Y

Optional. NULL (default): the n by n matrix of distances between the rows of X is returned; a single ranking (vector): the distances of each row of X from Y; a matrix of rankings: the nrow(X) by nrow(Y) matrix of distances.

dist

The distance: one of "kendall", "cayley", "hamming", "ulam", "footrule", "spearman" (square root of the sum of squared rank differences, as in Murphy and Martin, 2003) and "spearmansq" (sum of squared rank differences).

squared

For spearmand: if TRUE the sum of squared rank differences, without square root.

Details

With r and s two rankings of M objects:

All these distances are right-invariant (they do not depend on the labelling of the objects). Ties are not allowed.

Value

A matrix of distances, a vector, or a single number (see Y).

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

Diaconis, P. (1988). Group Representations in Probability and Statistics. IMS Lecture Notes - Monograph Series, 11.

Critchlow, D.E. (1985). Metric Methods for Analyzing Partially Ranked Data. Lecture Notes in Statistics 34, Springer.

See Also

mallows, mixdbm

Examples

r <- c(1, 2, 3, 4, 5)
s <- c(2, 1, 5, 3, 4)
kendalld(r, s)
cayleyd(r, s)
ulamd(r, s)
spearmand(r, s, squared = TRUE)
data(Irish)
## complete rankings only (rankings with ties are not supported yet)
X <- Irish$rankings[apply(Irish$rankings, 1, function(r) all(sort(r) == 1:5)), ]
D <- rankdist(X[1:10, ], dist = "footrule")


Projection of rankings on the principal planes of the permutation polytope

Description

Projects a set of rankings onto the directions along which they are farthest from the center of the permutation polytope (Marden, 1995, Section 2.2): the biplot of Cohen and Mallows (1980), similar to principal components but centred at the center of the polytope instead of at the mean ranking. The poles of the objects are projected too. Use plot to display the projection.

Usage

rankproj(X, wk = NULL, k = 2)

Arguments

X

A n by m data matrix (or data frame), in which there are n judges and m objects to be judged. Each row is a ranking of the objects, which are represented by the columns; ties are allowed, and so are missing values (NA or NaN) for objects not ranked by a judge (e.g. top-k partial rankings), which are treated as tied in the last position.

wk

Optional vector of n non-negative weights (e.g. the frequencies of the distinct rankings in the rows of X). Default NULL: every judge has weight 1.

k

The number of dimensions returned. Default 2; at most m - 1.

Details

Let y be the vector of the ranks given by a judge (with ties, the midranks of the buckets, so that the ranks sum to m(m + 1)/2) and c the center of the polytope, whose elements are all (m + 1)/2. The axes are the first k eigenvectors of W = \sum w (y - c)(y - c)' / \sum w, and their eigenvalues are the mean squared distances of the rankings from the center along each axis. The scores are the projections of y - c divided by the distance of a permutation from the center, \sqrt{m(m^2-1)/12}, so that they lie in the unit ball: permutations on its surface, rankings with ties inside.

The pole of an object (Marden, 1995, Definition 2.2) is the half line from the center through the average of the permutations that rank the object first (1 for the object, 1 + m/2 for the others): the closer a ranking to the pole, the better the rank of the object. The poles are returned as unit vectors projected on the axes, so their length (at most 1) tells how well the object is represented in the projection. The sign of each axis is chosen so that its largest loading is positive.

Value

An object of class rankproj, a list with:

scores the scores of the distinct rankings (one row each)
rankings the distinct rankings, in standard form (1, 2, ... for the buckets)
weights the number (total weight) of judges with each distinct ranking
idx the distinct ranking of each row of X (NA for rows with zero weight)
wk the weights of the rows of X (1 if not given)
poles the projected poles of the objects (one row each)
loadings the m by k matrix of the axes (eigenvectors)
eigenvalues all the non-zero eigenvalues of W
prop the proportion of the sum of the eigenvalues of each axis
nj the number of judges (the sum of the weights)
items the names of the objects

Author(s)

Luca Coraggio luca.coraggio@unina.it

References

Marden, J.I. (1995). Analyzing and Modeling Rank Data. Chapman & Hall, London.

Cohen, A., and Mallows, C.L. (1980). Analysis of ranking data. Technical memorandum, Bell Telephone Laboratories, Murray Hill, NJ.

See Also

plot.rankproj, marginals, pairmatrix

Examples

data(sports, package = "ConsRank")
pr <- rankproj(sports)
pr
plot(pr)
data(Univranks)
plot(rankproj(Univranks$rankings), groups = Univranks$predictors$Stud)


Recursive partitioning method for the prediction of preference rankings based upon Kemeny distances

Description

Recursive partitioning method for the prediction of preference rankings based upon Kemeny distances (D'Ambrosio and Heiser, 2016), or distance-based tree with a Mallows model within each node (Lee and Yu, 2010).

Usage

ranktree(Y, X, prunplot = FALSE, control = ranktreecontrol(...), ...)

Arguments

Y

A n by m data matrix, in which there are n judges and m objects to be judged. Each row is a ranking of the objects which are represented by the columns.

X

A dataframe containing the predictor, that must have n rows.

prunplot

prunplot=TRUE returns the plot of the pruning sequence. Default value: FALSE

control

a list of options that control details of the ranktree algorithm governed by the function ranktreecontrol. The options govern the minimum size within node to split (the default value is 0.1*n, where n is the total sample size), the bound on the decrease in impurity, (default, 0.01), the algorithm chosen to compute the median ranking (default, "quick"), and other options related to the consrank algorithm, which is called by ranktree

...

arguments passed bypassing ranktreecontrol

Details

The user can use any algorithm implemented in the consrank function from the ConsRank package ("BB", "quick", "fast", "decor" or "BOLT", see ranktreecontrol). All algorithms allow the user to set the option 'full=TRUE' if the median ranking(s) must be searched in the restricted space of permutations instead of in the unconstrained universe of rankings of n items including all possible ties. The output consists in a object of the class "ranktree". It contains:

X the predictors: it must be a dataframe
Y the response variable: the matrix of the rankings
node a list containing teh tree-based structure:
number node number
terminal logical: TRUE is terminal node
father father node number of the current node
idfather id of the father node of the current node
size sample size within node
impur impurity at node
wimpur weighted impurity at node
idatnode id of the observations within node
class median ranking within node in terms of orderings
nclass median ranking within node in terms of rankings
mclass eventual multiple median rankings
tau Tau_x rank correlation coefficient at node
wtau weighted Tau_x rank correlation coefficient at node
error error at node
werror weighted error at node
varsplit variables generating split
varsplitid id of variables generating split
cutspli splitting point
children children nodes generated by current node
idchildren id of children nodes generated by current node
... other info about node
control parameters used to build the tree
numnodes number of nodes of the tree
tsynt list containing the synthesis of the tree:
children list containing all information about leaves
parents list containing all information about parent nodes
geneaoly data frame containing information about all nodes
idgenealogy data frame containing information about all nodes in terms of nodes id
idparents id of the parents of all the nodes
goodness goodness -and badness- of fit measures of the tree: Tau_X, error, impurity (with model = "mallows" also deviance, log-likelihood, number of parameters, AIC, BIC)
nomin information about nature of the predictors
alpha alpha parameter for pruning sequence
pruneinfo list containing information about the pruning sequence:
prunelist information about the pruning
tau tau_X rank correlation coefficient of each subtree
error error of each subtree
termnodes number of terminal nodes of each subtree
deviance (model = "mallows" only) deviance of each subtree
ktop (model = "mallows" only) number of ranked positions of each ranking (M - 1 for complete rankings)
subtrees list of each subtree created with the cost-complexity pruning procedure

Models. Two approaches are available, chosen with the option model of ranktreecontrol.

With model = "kemeny" (default) the tree is the recursive partitioning method of D'Ambrosio and Heiser (2016): the impurity of a node is based on Kemeny distances, and the class of a node is its median ranking computed with consrank. With impurity = "pairwise" (default) the impurity is the sum of the Kemeny distances between all the pairs of rankings within the node, divided by its size, as in D'Ambrosio and Heiser (2016): the splits do not depend on the median rankings, so the tree is the same with any algorithm. With impurity = "median" the impurity of a node is the sum of the Kemeny distances of its rankings from its median ranking (impur is this sum divided by the size of the node, i.e. the mean distance from the median, and wimpur is the sum divided by the sample size), and the best split maximises the decrease of this sum, divided by the sample size. The median rankings of the two children of every candidate split are computed from their combined input matrices (updated by cumulative sums over the cutting points of ordered predictors), so the class of a node is exactly the median ranking used for its impurity. With a heuristic algorithm the decrease of a split can be slightly negative.

Objects not ranked. With model = "kemeny" the objects not ranked by a judge are coded as NA, and the option unranked of ranktreecontrol says how they are treated. With unranked = "last" (default) they are tied in the position after the last object ranked by the judge, as in D'Ambrosio and Heiser (2016), and the rankings stored in the tree (Y) are completed in this way. With unranked = "unknown" (only with impurity = "median") they come after the ranked objects, but their order is unknown: a pair of two objects not ranked by a judge is not observed, and it counts neither as a preference nor as a tie. The combined input matrix of a node then counts, for each pair, only the judges who rank at least one of its objects, and the impurity is the sum of the Kemeny distances from the median ranking computed on the observed pairs; tau and error of the nodes are the averaged \tau_X and the normalized Kemeny distance on the observed pairs, and so are prunecost = "error" and the measures of validatetree. For top-k lists ("choose and rank k objects out of n") this convention uses all the information given by the judges, and nothing more: the combined input matrix is the average of the matrices obtained by completing each top-k list in all the possible ways. The rankings stored in the tree keep the NA.

The consensus of the nodes can be constrained with one of the options nbuckets (median bucket order with a fixed number of buckets), bucketsizes (median bucket order with a pattern of bucket sizes) and topk (median top-k list) of ranktreecontrol, computed by mcbo and consranktopk from the combined input matrix of the node. The class of each node is then the constrained consensus, and so are the measures based on it (tau, error, validatetree, predict). With impurity = "pairwise" the tree is the same as without the constraint and only the classes change; with impurity = "median" the impurity is the sum of the distances from the constrained consensus, so the constraint drives the choice of the splits. No probability model is assumed, and the rankings can contain ties: the Kemeny distance is twice the Kendall distance for complete rankings, and is defined also for rankings with ties.

With model = "mallows" the tree is the distance-based tree of Lee and Yu (2010): a Mallows model with Kendall distance is fitted by maximum likelihood within each node. The class of the node is the modal ranking of the model and the impurity is its deviance (-2 times the log-likelihood) divided by the size of the node. The best split maximises the decrease in deviance D_{father} - D_{left} - D_{right}, divided by the sample size (so decrmin is on this scale), and splits leaving in a child node fewer than minprop times the judges of the father node (default 10%, as in Lee and Yu, 2010) are not considered. The cost-complexity pruning uses the deviance of the leaves. The nodes contain also lambda (the precision parameter of the Mallows model) and deviance; goodness contains the deviance, the log-likelihood, the number of parameters (one precision for each leaf and one for each split, the modal rankings are not counted, as in Lee and Yu, 2010), AIC and BIC of the tree, and pruneinfo the deviance of the subtrees. The measures based on Kemeny distances (tau, error) are computed as well, but print, summary, plot and validatetree report the measures of the Mallows models.

The "mallows" model handles complete rankings and top-k partial rankings ("pick k out of M", as Inglehart's items in the EVS data). The unranked objects are coded as NA, or tied in the last position, and are assumed to be in unknown order: the probability of a top-k ranking is the sum of the probabilities of all its compatible complete rankings, as in Lee and Yu (2010). It is computed exactly in closed form (Fligner and Verducci, 1986), so the number of unranked objects is not limited. Rankings with ties among the ranked objects are not allowed (an error is returned): a tie expresses indifference, which a model on permutations cannot represent. The rankings stored in the tree (Y) are in standard form: ranked objects in positions 1, ..., k and unranked objects tied in position k + 1.

The modal ranking of a node is the Kemeny median ranking restricted to permutations of the pairs ordered by the rankings, which for the Mallows model does not depend on \lambda. With up to 8 objects it is computed exactly by exhaustive search; with more objects the split search uses a local search (insertions of single objects), and the modal ranking of the nodes of the tree is computed with the branch-and-bound algorithm of consrank (algorithm = "BB", full = TRUE), which can be slow for many objects. When all the rankings of a node are equal to its modal ranking, \lambda is set to lambdamax.

Differences from Lee and Yu (2010): the parameters are maximum likelihood estimates computed exactly; weighted distances, \phi-component models and distances other than Kendall are not available; the growth of the tree is governed by num and decrmin as for the other model (Lee and Yu do not split nodes with fewer than 200 judges, which corresponds to num = 200), and the pruning sequence is validated with validatetree, which returns the deviance of the subtrees and the 1-SE choice.

Value

An object of the class ranktree. See details for detailed information.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

D'Ambrosio, A., and Heiser W.J. (2016). A recursive partitioning method for the prediction of preference rankings based upon Kemeny distances. Psychometrika, vol. 81 (3), pp.774-94.

Lee, P.H., and Yu, P.L.H. (2010). Distance-based tree models for ranking data. Computational Statistics and Data Analysis, 54, 1672-1682.

Fligner, M.A., and Verducci, J.S. (1986). Distance based ranking models. Journal of the Royal Statistical Society B, 48, 359-369.

See Also

ranktreecontrol, plot.ranktree, summary.ranktree, getsubtree, validatetree, treepaths, nodepath

Examples

data("Univranks")
tree <- ranktree(Univranks$rankings,Univranks$predictors,num=50)


data(Irish)
#build the tree with default options
tree <- ranktree(Irish$rankings,Irish$predictors)

#plot the tree
plot(tree,dispclass=TRUE)

#visualize information
summary(tree)

#get information about the paths leading to terminal nodes (all the paths)
infopaths <- treepaths(tree)

#the terminal nodes
infopaths$leaves

#sample size within each terminal node
infopaths$size

#visualize the path of the second leave (terminal node number 8)
infopaths$paths[[2]]

#alternatively
nodepath(termnode=8,tree)


set.seed(132) #for reproducibility
#validation of the tree via v-fold cross-validation (default value of V=5)
vtree <- validatetree(tree,method="cv")

#extract the "best" tree
dtree <- getsubtree(tree,vtree$best_tau)

summary(dtree)

#plot the validated tree
plot(dtree,dispclass=TRUE)

#predicted rankings
rankfit <- predict(dtree,newx=Irish$predictors)

#fit of rankings
rankfit$rankings

#fit in terms of orderings
rankfit$orderings

#all info about the fit (id og the leaf, predictor values, and fit)
rankfit$orderings

#distance-based tree (Lee and Yu, 2010): Mallows model within the nodes, top-2 rankings
#of Inglehart's items, the unranked items (NaN) are in unknown order
data(EVS)
set.seed(654)
training <- sample(1911,1433)
mtree <- ranktree(EVS$rankings[training,],EVS$predictors[training,],model="mallows",
                  decrmin=0,num=200)
mtree
#deviance of the test rankings along the pruning sequence, and 1-SE choice
vmtree <- validatetree(mtree,testX=EVS$predictors[-training,],testY=EVS$rankings[-training,])
vmtree$deviance
mtree1se <- getsubtree(mtree,vmtree$best_deviance1se)
summary(mtree1se)
plot(mtree1se,dispclass=TRUE)




Utility function

Description

Utility function to use to set the control arguments of ranktree

Usage

ranktreecontrol(
  num = NULL,
  decrmin = 0.01,
  algorithm = "quick",
  full = FALSE,
  itermax = 10,
  np = 15,
  gl = 100,
  ff = 0.4,
  cr = 0.9,
  proc = FALSE,
  ps = FALSE,
  prunecost = c("impurity", "error"),
  model = c("kemeny", "mallows"),
  impurity = "pairwise",
  dist = "kendall",
  minprop = NULL,
  lambdamax = 50,
  otp = TRUE,
  maxjudges = Inf,
  maxcuts = NULL,
  nbuckets = NULL,
  bucketsizes = NULL,
  topk = NULL,
  unranked = c("last", "unknown")
)

Arguments

num

The maximum number of observations in a node to be split: default, 10% of the sample size

decrmin

Minimum decrease in impurity (model = "kemeny") or in deviance divided by the sample size (model = "mallows") to split a node

algorithm

(model = "kemeny" only) The algorithm used to compute the median ranking. One among "BB", "quick" (default), "fast", "decor" and "BOLT" (the name is matched ignoring the case). "BOLT" is the deterministic heuristic of bolt, fast also with many objects

full

(model = "kemeny" only) Specifies if the median ranking must be searched in the universe of rankings including all the possible ties. Default: FALSE

itermax

(model = "kemeny" only) Number of iterations for "fast" and "decor" algorithms. itermax=10 is the default option.

np

(model = "kemeny", for "decor" only) the number of population individuals. np=15 is the default option.

gl

(model = "kemeny", for"decor" only) generations limit, maximum number of consecutive generations without improvement. gl=100 is the default option.

ff

(model = "kemeny", for"decor" only) the scaling rate for mutation. Must be in [0,1]. ff=0.4 is the default option.

cr

(model = "kemeny", for"decor" only) the crossover range. Must be in [0,1]. cr=0.9 is the default option.

proc

(model = "kemeny", for "BB" only) proc=TRUE allows the branch and bound algorithm to work in difficult cases, i.e. when the number of objects is larger than 15 or 25. proc=FALSE is the default option

ps

(model = "kemeny" only) If PS=TRUE, on the screen some information about how many branches are processed are displayed. Default value: FALSE

prunecost

(model = "kemeny" only) The cost used by the cost-complexity pruning: "impurity" (default, the within-node impurity used to grow the tree, as in D'Ambrosio and Heiser, 2016) or "error" (the Kemeny distance between the rankings and the median ranking of each node, i.e. the same measure used by validatetree to evaluate the subtrees). With model = "mallows" the pruning always uses the deviance of the leaves

model

The approach used to build the tree: "kemeny" (default; the impurity of a node is based on Kemeny distances, D'Ambrosio and Heiser, 2016) or "mallows" (a Mallows model is fitted within each node and the impurity is its deviance, Lee and Yu, 2010). See Details of ranktree

impurity

(model = "kemeny" only) The impurity of a node: "pairwise" (default, the sum of the Kemeny distances between all the pairs of rankings within the node, divided by its size, as in D'Ambrosio and Heiser, 2016) or "median" (the sum of the Kemeny distances of the rankings of the node from its median ranking, computed with algorithm). With "pairwise" the splits do not depend on the median rankings; with "median" every candidate split requires the median rankings of the two child nodes. See Details of ranktree

dist

(model = "mallows" only) The distance of the Mallows model. Only "kendall" is available at present

minprop

(model = "mallows" only) Minimum size of each child node, as a proportion of the size of the node to be split. Default (NULL): 0.1, as in Lee and Yu (2010)

lambdamax

(model = "mallows" only) Upper bound for the precision parameter \lambda of the Mallows model (reached when all the rankings in a node are equal to its modal ranking). Default: 50

otp

(model = "kemeny", for "BOLT" only) If TRUE (default), the optimal tie partitioning step of BOLT is used (see bolt)

maxjudges

(model = "kemeny", for "BOLT" only) Maximum number of distinct rankings of the judges of a node used by BOLT as starting solutions. Default Inf (all of them). Not used with impurity = "median", where the median rankings are computed from the combined input matrices of the nodes

maxcuts

(model = "kemeny" with impurity = "median" only) The maximum number of cutting points considered for an ordered predictor (numeric or ordered factor) in a node. Default NULL: all the cutting points (the exact search). With an integer K, when a predictor has more than K cutting points in a node only K of them are considered, those that leave in the left child the proportions 1/(K+1), 2/(K+1), ..., K/(K+1) of the judges of the node (or the nearest ones): the search is much faster with continuous predictors, at the price of possibly missing the best split. Nominal predictors are not affected

nbuckets

(model = "kemeny" only) If given, the consensus of each node is the median bucket order with exactly nbuckets buckets (computed by mcbo with algorithm, which must be "BB", "quick", "decor" or "BOLT"). Default NULL: no constraint

bucketsizes

(model = "kemeny" only) If given, the consensus of each node is the median bucket order with this pattern of bucket sizes, from the first (top) bucket to the last: each element is a prescribed size or NA (free size), as in mcbo. Requires algorithm = "BOLT". Default NULL: no constraint

topk

(model = "kemeny" only) If given, the consensus of each node is the median top-k list of length topk (the top-k consensus, computed by consranktopk: the topk objects in positions 1, ..., k and the others tied in position k + 1), with the exact algorithm of consranktopk, or with its BOLT heuristic when algorithm = "BOLT". Not to be confused with top-k data (see model = "mallows"). Default NULL: no constraint. At most one of nbuckets, bucketsizes and topk can be given, and not with full = TRUE

unranked

(model = "kemeny" only) How the objects not ranked by a judge (coded as NA) are treated: "last" (default) or "unknown". With "last" the objects not ranked by a judge are tied in the position after his or her last ranked object, as in D'Ambrosio and Heiser (2016): two such objects count as a tie, and each of them comes after every ranked object. With "unknown" the objects not ranked by a judge come after his or her ranked objects, but their order is unknown: a pair of two such objects is not observed and does not count, neither as a preference nor as a tie. This is the natural convention for top-k lists ("choose and rank k objects out of n"), and it requires impurity = "median": the impurity, tau and error of the nodes, prunecost = "error" and validatetree are then computed on the observed pairs only. Without missing values the two options give the same tree

Details

The options that do not concern the chosen model are ignored, with a warning if they are set explicitly.

Value

A list containing all the control parameters

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

D'Ambrosio, A., and Heiser W.J. (2016). A recursive partitioning method for the prediction of preference rankings based upon Kemeny distances. Psychometrika, vol. 81 (3), pp.774-94.

Lee, P.H., and Yu, P.L.H. (2010). Distance-based tree models for ranking data. Computational Statistics and Data Analysis, 54, 1672-1682.

See Also

ranktree


Simulation and density of the Mallows model

Description

rmallows draws rankings from the Mallows (distance-based) model P(r) = C(\lambda) \exp\{-\lambda d(r, R)\}; dmallows computes its probability (density) for given rankings.

Usage

rmallows(n, center, lambda, dist = "kendall")

dmallows(X, center, lambda, dist = "kendall", log = FALSE)

Arguments

n

Number of rankings to draw.

center

The central (modal) ranking R (vector; rank of object j in position j). Its names, if any, become the column names.

lambda

The precision parameter, \lambda \ge 0.

dist

The distance (see rankdist).

X

A matrix (or vector) of complete rankings.

log

If TRUE the log-probabilities.

Details

Sampling is exact for every distance: inversion vectors (Kendall), the Chinese restaurant process for the Ewens distribution (Cayley), random derangements (Hamming), random standard Young tableaux and inverse Robinson-Schensted correspondence (Ulam, M \le 50), dynamic programming (footrule and Spearman, M \le 14).

Value

rmallows: a n by M matrix of rankings. dmallows: a vector of probabilities.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mallows, rmixdbm

Examples

set.seed(1)
X <- rmallows(100, center = 1:6, lambda = 1, dist = "kendall")
head(X)
dmallows(X[1:5, ], center = 1:6, lambda = 1, dist = "kendall")


Simulate from a mixture of distance-based models

Description

Simulate from a mixture of distance-based models

Usage

rmixdbm(n, centers, lambda, p, dist = "kendall")

Arguments

n

Number of rankings.

centers

A G by M matrix of central rankings (or a vector if G = 1).

lambda

Vector of G precisions.

p

Vector of G mixing proportions, or G + 1 with the last one for a uniform noise component.

dist

The distance (see rankdist).

Value

A n by M matrix of rankings with attribute "component".

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbm, rmallows

Examples

set.seed(4)
X <- rmixdbm(500, centers = rbind(1:5, 5:1), lambda = c(1, 1),
             p = c(0.5, 0.5), dist = "kendall")
table(attr(X, "component"))


S3 methods for ranktree

Description

Summary methods for objects of class cca

Usage

## S3 method for class 'cca'
summary(object, ...)

Arguments

object

An object of the class "cca"

...

not used

Value

it shows the summary of the prediction tree


S3 methods for kunfolding

Description

Summary methods for objects of class kunfolding

Usage

## S3 method for class 'kunfolding'
summary(object, ...)

Arguments

object

An object of the class "kunfolding"

...

not used

Value

it shows the summary of the Kemeny equivalent augmented unfolding


Summary method for mallows objects

Description

As print, plus the expected distance under the uniform model, an approximate 95% confidence interval for the precision (conditional on the estimated center) and the BIC.

Usage

## S3 method for class 'mallows'
summary(object, digits = 4, ...)

Arguments

object

An object of class "mallows".

digits

Number of significant digits.

...

Not used.

Value

The object, invisibly.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mallows


Summary method for mixdbm objects

Description

As print, plus the size of each cluster of the crisp partition, the mean posterior probability within each cluster, the convergence of the EM algorithm, how many random starts reached the best log-likelihood (an indication of local maxima) and how many degenerate starts were discarded.

Usage

## S3 method for class 'mixdbm'
summary(object, digits = 3, ...)

Arguments

object

An object of class "mixdbm".

digits

Number of significant digits.

...

Not used.

Value

The object, invisibly.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbm


Summary method for mixdbmselect objects

Description

As print, plus the full printout of the models chosen by BIC and by ICL.

Usage

## S3 method for class 'mixdbmselect'
summary(object, top = 10, ...)

Arguments

object

An object of class "mixdbmselect".

top

Number of models shown for each criterion.

...

Not used.

Value

The object, invisibly.

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

mixdbmselect


S3 methods for ranktree

Description

Summary methods for objects of class ranktree

Usage

## S3 method for class 'ranktree'
summary(object, ...)

Arguments

object

An object of the class "ranktree"

...

not used

Value

it shows the summary of the prediction tree. For a tree built with model = "mallows" (see ranktree) it shows, for each leaf, the modal ranking and the precision \lambda of the Mallows model, \phi = e^{-\lambda}, the expected Kendall distance of a complete ranking from the modal ranking and the log-likelihood of the rankings in the leaf, and it returns (invisibly) these values as a data frame. For the other trees it returns (invisibly) the paths of the leaves, as given by treepaths

Examples


data("Univranks")
tree <- ranktree(Univranks$rankings,Univranks$predictors,num=50)
summary(tree)


Path of a terminal node

Description

Given an object of the class "ranktree", it extracts the paths of all terminal nodes

Usage

treepaths(Tree)

Arguments

Tree

An object of the class "ranktree"

Value

A list containing:

leaves the number of the terminal nodes
size the sample size within each terminal nodes
paths a list containing all the paths

Author(s)

Antonio D'Ambrosio antdambr@unina.it

See Also

ranktree, nodepath, getsubtree

Examples


data(Irish)
#build the tree with default options
tree <- ranktree(Irish$rankings,Irish$predictors)
#get information about all the paths leading to terminal nodes
paths <- treepaths(tree)
#
#the terminal nodes
paths$leaves
#
#sample size within each terminal node
paths$size
#
#visualize the path of the second leave (terminal node number 8)
paths$paths[[2]]




Validation of the tree for preference rankings

Description

Validation of the tree either with a test set procedure or with v-fold cross validation

Usage

validatetree(
  Tree,
  testX = NULL,
  testY = NULL,
  method = "test",
  V = 5,
  plotting = TRUE,
  se = 0
)

Arguments

Tree

An object of the class "ranktree" coming form the function ranktree

testX

The data frame containing the test set (predictors)

testY

The matrix obtaining the test set (response)

method

One between "test" (default) or "cv"

V

The cross-validation parameter. Default V=5

plotting

With the default option plotting=TRUE, the pruning sequence plot is visualized

se

The multiplier s of the s-SE rule (see Details). Default se = 0: the chosen subtree is the one with the largest Tau_x (best_tau); se = 1 gives the 1-SE rule of Breiman et al. (1984).

Details

With model = "mallows" the test rankings can be top-k partial rankings as for ranktree (unranked objects coded as NA or tied in the last position). With model = "kemeny" the objects not ranked (NA) in the test rankings are treated as in the tree (option unranked of ranktreecontrol): with "last" they are tied after the last ranked object; with "unknown" tau and error are computed on the observed pairs only.

Standard error of Tau_x and s-SE rule. Each subtree is evaluated on m judges: the judges of the test set, or, with method = "cv", all the judges, each of them predicted by the tree grown without its fold. With unranked = "last" the Tau_x of a subtree is the mean of the Tau_x \tau_h between the rankings of the judges and the classes of their leaves, \bar\tau = \sum_h \tau_h / m, and its standard error is

SE = \sqrt{\sum_h (\tau_h - \bar\tau)^2 / (m(m-1))},

i.e. the standard deviation of the \tau_h divided by \sqrt m. With unranked = "unknown" the Tau_x is computed on the pairs observed by each judge: \bar\tau = \sum_h a_h / \sum_h O_h, where O_h is the number of pairs observed by the judge h and a_h = O_h - G_h, G_h being the Kemeny distance between the judge and its class on these pairs. This is a ratio estimator, whose standard error is (first-order approximation)

SE = \sqrt{\sum_h (a_h - \bar\tau O_h)^2 / (m(m-1))} / \bar O,

with \bar O = \sum_h O_h / m; when all the judges observe the same number of pairs it coincides with the previous formula. The s-SE rule chooses the smallest subtree whose Tau_x is at least \bar\tau_{max} - s\,SE_{max}, where \bar\tau_{max} is the largest Tau_x of the sequence and SE_{max} its standard error (Breiman et al., 1984, Section 3.4.3). With cross-validation the \tau_h are not independent, because the trees of the folds share most of the judges, and the standard error is only an approximation, as for the classification and regression trees (Breiman et al., 1984, Section 11.5).

Value

A list containing:

tau the Tau_x rank correlation coefficient of the sequence of the trees
error the error of the sequence of the trees
termnodes the number of terminal nodes of the sequence of the trees
best_tau the best tree in terms of Tau_x rank correlation coefficient
best_error the best tree in terms of error (it is the same)
tause the standard error of the Tau_x of the sequence of the trees
se the multiplier s of the s-SE rule
best_tause the tree chosen by the s-SE rule (with se = 0, best_tau)
validation information about the validation procedure

If the tree was built with model = "mallows" (see ranktree) the subtrees are evaluated by the deviance of the Mallows models of their leaves, and the list contains:

termnodes the number of terminal nodes of the sequence of the trees
deviance the mean deviance per ranking, -2 times the mean log-likelihood of the test (or cross-validated) rankings under the Mallows models of the leaves, of the sequence of the trees
devse the standard error of the mean deviance
best_deviance the best tree in terms of deviance
best_deviance1se the smallest tree whose deviance is within one standard error of the minimum (1-SE rule, as in Lee and Yu, 2010)
se the multiplier s of the s-SE rule
best_deviancese the smallest tree whose deviance is within s standard errors of the minimum (with se = 0, best_deviance; with se = 1, best_deviance1se)
validation information about the validation procedure

Author(s)

Antonio D'Ambrosio antdambr@unina.it

References

Breiman, L., Friedman, J.H., Olshen, R.A., and Stone, C.J. (1984). Classification and Regression Trees. Wadsworth, Belmont, CA.

Lee, P.H., and Yu, P.L.H. (2010). Distance-based tree models for ranking data. Computational Statistics and Data Analysis, 54, 1672-1682.

Examples


data(EVS)
EVS$rankings[is.na(EVS$rankings)] <- 3
set.seed(654)
training=sample(1911,1434)
tree <- ranktree(EVS$rankings[training,],EVS$predictors[training,],decrmin=0.001,num=50)
#test set validation
vtreetest <- validatetree(tree,testX=EVS$predictors[-training,],EVS$rankings[-training,])
#the same with the 1-SE rule
vtree1se <- validatetree(tree,testX=EVS$predictors[-training,],EVS$rankings[-training,],
                         plotting=FALSE,se=1)
vtree1se$best_tause
#cross-validation
vtreecv <- validatetree(tree,method="cv",V=10) 



Tau_x rank correlation coefficient for vectors

Description

Tau_x rank correlation coefficient for large vectors

Usage

vecTaux(X, Y)

Arguments

X

A vector of length n

Y

A vector of length n

Value

The tau_x rank correlation coefficient between the 2 vectors