Skip to content

Commit

Permalink
add helper number_unnamed function (see #18)
Browse files Browse the repository at this point in the history
  • Loading branch information
timelyportfolio committed Nov 1, 2016
1 parent 6e6bc8b commit 2d64375
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 2 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Expand Up @@ -3,6 +3,7 @@
export(jsonedit)
export(jsoneditOutput)
export(jsonedit_gadget)
export(number_unnamed)
export(reactjson)
export(reactjsonOutput)
export(renderJsonedit)
Expand Down
3 changes: 2 additions & 1 deletion NEWS.md
@@ -1,7 +1,8 @@
# listviewer 1.4.0

* add `elementId` to the `jsonedit` function
* update `react-json` to [`0.2.1`]
* update `react-json` to [`0.2.1`](https://github.com/arqex/react-json/releases/tag/0.2.1)
* add helper `number_unnamed` function (see [issue](https://github.com/timelyportfolio/listviewer/issues/18))

# listviewer 1.3

Expand Down
57 changes: 56 additions & 1 deletion R/utils.R
@@ -1,5 +1,4 @@
#' @keywords internal

named_vec2list <- function(listx){
# to avoid toJSON keep_vec_names warnings
# with named vectors
Expand All @@ -22,3 +21,59 @@ list_proper_form <- function(listdata){
}
}

#' Recurse Over Nested Lists
#'
#' Like \code{rapply} but recurses over nested lists and
#' retain \code{attributes} and \code{names}.
#'
#' @param l \code{list} over which we would like to recurse
#' @param func \code{function} to apply to the list
#' @param ... arguments for the \code{func}
#'
#' @keywords internal
recurse <- function(l, func, ...) {
l <- func(l, ...)
if(is.list(l) && length(l)>0){
lapply(
l,
function(ll){
recurse(ll, func, ...)
}
)
} else {
l
}
}

#' @keywords internal
add_number_names <- function(l){
if(length(l)>0 && is.null(names(l))){
names(l) <- seq_len(length(l))
}
l
}


#' Number Starting at \code{1}
#'
#' JavaScript starts at \code{0}, but R starts at \code{1}.
#' This means unnamed lists and vectors are indexed starting at
#' \code{0} in listviewer widgets. This little helper function
#' tries to resolve the disconnect by assigning sequential numbers
#' starting at \code{1} to names for unnamed \code{lists} and \code{vectors}.
#' Please note though that using \code{number_unnamed} will potentially
#' cause difficulties serializing back and forth between JavaScript and R.
#'
#' @param l \code{list}
#'
#' @examples
#' library(listviewer)
#' jsonedit(
#' number_unnamed(list(x=list(letters[1:3])))
#' )
#'
#' @export

number_unnamed <- function(l) {
recurse(l, add_number_names)
}
28 changes: 28 additions & 0 deletions man/number_unnamed.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions man/recurse.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 2d64375

Please sign in to comment.