# create rankings from data in long form
# Example long-form data
x <- data.frame(
id = c(rep(1:4, each = 4), 5, 5, 5),
item = c(
LETTERS[c(1:3, 3, 1:4, 2:5, 1:2, 1)], NA,
LETTERS[3:5]
),
rank = c(4:1, rep(NA, 4), 3:4, NA, NA, 1, 3, 4, 2, 2, 2, 3)
)
# * Set #1 has two different ranks for the same item (item C
# has rank 1 and 2). This item will be excluded from the preferences.
# * All ranks are missing in set #2, a technically valid partial ordering
# * Some ranks are missing in set #3, a perfectly valid partial ordering
# * Set #4 has inconsistent ranks for two items, and a rank with a
# missing item.
# * Set #5 is not a dense ranking. It will be converted to be dense and then
# inferred to be a regular partial ordering with ties.
split(x, x$rank)
# Creating a preferences object with this data will attempt to resolve these
# issues automatically, sending warnings when assumptions need to be made.
preferences(x, id = "id", item = "item", rank = "rank")
# Convert an existing matrix of rankings to a preferences object.
rnk <- matrix(c(
1, 2, 0, 0,
4, 1, 2, 3,
2, 1, 1, 1,
1, 2, 3, 0,
2, 1, 1, 0,
1, 0, 3, 2
), nrow = 6, byrow = TRUE)
colnames(rnk) <- c("apple", "banana", "orange", "pear")
rnk <- as.preferences(rnk, format = "ranking")
# Convert an existing data frame of orderings to a preferences object.
e <- character() # short-hand for empty ranks
ord <- preferences(
as.data.frame(
rbind(
list(1, 2, e, e), # apple, banana
list("banana", "orange", "pear", "apple"),
list(c("banana", "orange", "pear"), "apple", e, e),
list("apple", "banana", "orange", e),
list(c("banana", "orange"), "apple", e, e),
list("apple", "pear", "orange", e)
)
),
format = "ordering",
item_names = c("apple", "banana", "orange", "pear")
)
# Access the first three sets of preferences
ord[1:3, ]
# Truncate preferences to the top 2 ranks
ord[, 1:2, by_rank = TRUE]
# Exclude pear from the rankings
ord[, -4]
# Get the highest-ranked items and return as a data.frame of orderings
ord[, 1, by_rank = TRUE, as.ordering = TRUE]
# Convert the preferences to a ranking matrix
as.matrix(ord)
# Get the rank of apple in the third preference-set
as.matrix(ord)[3, 1]
# Get all the ranks assigned to apple as a vector
as.matrix(ord)[, "apple"]
Run the code above in your browser using DataLab