#' Select/rename variables by name
#'
#' \code{select} and \code{rename} methods for lists. The \code{select} method
#' is defined for lists, while when working with objects of other classes it
#' uses dplyr's \code{\link[dplyr]{select}}.
#'
#' @param .data a list.
#' @param \dots one or more unquoted expressions separated by commas.
#' You can treat variable names like they are positions.
#' Positive values select variables; negative values to drop
#' variables. If the first expression is negative, \code{select()}
#' will automatically start with all variables.
#' @param warn throw warnings when encountering errors in selecting variables
#' (\code{FALSE} by default).
#'
#' @seealso \code{\link[dplyr]{select}}, \code{\link[dplyr]{rename}}
#'
#' @examples
#'
#' as_lov(mtcars) %>%
#' select(mpg, cyl)
#'
#' as_lov(mtcars) %>%
#' rename(XXX_mpg = mpg)
#'
#' as_lol(mtcars) %>%
#' select(mpg, cyl) %>%
#' .[1:5]
#'
#' @export
select_list <- function(.data, ..., warn = TRUE) {
if (!is_simple_list(.data))
stop(".data is not a list")
dots <- quos(...)
if (length(dots) == 0L)
return(.data)
lapply(.data, function(.x) {
vars <- try_select_vars(names(.x), dots, warn = warn)
.x[vars]
})
}
#' @rdname select_list
#' @export
select <- function(.data, ..., warn = TRUE) {
# this hack is needed as select.list already exists in utils
if (is_simple_list(.data)) {
select_list(.data, ..., warn = warn)
} else {
dplyr::select(.data, ...)
}
}
#' @rdname select_list
#' @export
rename.list <- function(.data, ...) {
dots <- quos(...)
lapply(.data, function(.x) {
names(.x) <- names(rename_vars(names(.x), !!! dots,
strict = FALSE))
.x
})
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.