R/composer_vector.R

#' create a composer_vector or convert to one
#'
#' @param ... vector elements or vector to transform
#' @export
#' @examples
#' co(1:4)
#' co(1,2,3,4)
#' co(1:2,3:4)
#' co(list(1:2,3:4))
co <- function(...){
  UseMethod("co")
}

#' @export
co.default <- function(...){
  x <- unlist(list(...), recursive = FALSE)
  if(inherits(x,"composer_vector")) x else {
    class(x) <- c("composer_vector",class(x))}
  x
}

#' Apply co on subelements
#'
#' Can be used on lists but won't by default.
#' The input's class is not altered, the classes of its subelements are
#' @param x a data.frame, or a list
#' @param all logical, if TRUE co will be applied on all columns
#' @param ... unused
#' @export
#' @examples
#' co(head(iris))[["Species"]][[1,3]]
co.data.frame <- function(x, all = FALSE, ...){
  if (all) x[] <- lapply(x, co.default) else
    x <- purrr::modify_if(x,~is.vector(.) | !is.list(.), co.default)
  x
}

#' remove composer_vector class
#'
#' @param x
#' @export
unco <- function(x){
  UseMethod("unco")
}

#' @export
unco.default <- function(x){
  class(x) <- setdiff(class(x), "composer_vector")
  x
}

#' @export
unco.data.frame <- function(x){
  x[] <- lapply(x,unco.default)
  x
}


#' print a composer_vector object
#'
#' @param x
#' @export
print.composer_vector <- function(x){
  class(x) <- setdiff(class(x),"composer_vector")
  print(x)
  invisible(co(x))
}
moodymudskipper/composer documentation built on May 17, 2019, 3 p.m.