Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created September 19, 2019 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alandipert/7da41616548def947fdca7feca6424a5 to your computer and use it in GitHub Desktop.
Save alandipert/7da41616548def947fdca7feca6424a5 to your computer and use it in GitHub Desktop.
# Like choicesWithNames(), but returns a data frame of value, label, and
# optgroup columns. This rectangular view could also be thought of as the set
# of paths into the choicesWithNames() tree.
#
# For example, given a choices argument like this:
#
# list(a = 1, B = list(B = 2), c = list(3))
#
# choicesWithNames() would return a tree like this:
#
# list(a = "1", B = list(B = "2"), c = "3")
#
# and choicesWithNamesRectangle() would return an equivalent "rectangular"
# representation as a data frame:
#
# label value optgroup
# a 1
# B 2 B
# c 3
choicesWithNamesRectangle <- function(choices) {
label <- character()
value <- character()
optgroup <- character()
choiceTree <- choicesWithNames(choices)
for (i in seq_along(choiceTree)) {
# If this element is a list, then it's an group. Each sub-element
# should be added with a group name.
if (is.list(choiceTree[[i]])) {
for (j in seq_along(choiceTree[[i]])) {
label[length(label)+1] <- names(choiceTree[[i]])[[j]]
value[length(value)+1] <- choiceTree[[i]][[j]]
optgroup[length(optgroup)+1] <- names(choiceTree)[[i]]
}
# If this element isn't a list, then it's a leaf node with no group.
} else {
label[length(label)+1] <- names(choiceTree)[[i]]
value[length(value)+1] <- choiceTree[[i]]
optgroup[length(optgroup)+1] <- ""
}
}
data.frame(
label = label,
value = value,
optgroup = optgroup,
stringsAsFactors = FALSE,
row.names = NULL
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment