R/lov_and_lol.R

#' Convert data.frame or matrix to list-of-lists or list-of-vectors
#'
#' @param x a data.frame, matrix, or list.
#'
#' @examples
#'
#' as_lol(mtcars)
#' as_lov(mtcars)
#'
#' @export

as_lol <- function(x) {
  if (!is.data.frame(x) && !is.matrix(x)) {

    if (is.list(x)) {
      return(lapply(x, function(y) {
        tmp <- as.list(y)
        if (length(tmp) != length(y))
          stop("object cannot be automatically converted to list-of-lists")
        tmp
      }))
    }

    stop("as_lol method works only with data.frame, matrix and list objects")
  }

  apply(x, 1, as.list)
}

#' @rdname as_lol
#' @export

as_lov <- function(x) {
  if (!is.data.frame(x) && !is.matrix(x)) {

    if (is.list(x)) {
      return(lapply(x, function(y) {
        tmp <- unlist(y)
        if (length(tmp) != length(y))
          stop("object cannot be automatically converted to list-of-vectors")
        names(tmp) <- names(y)
        tmp
      }))
    }

    stop("to_lov method works only with data.frame, matrix and list objects")
  }

  out <- lapply(1:nrow(x), function(i) {
    tmp <- unlist(x[i, ])
    names(tmp) <- colnames(x)
    tmp
  })
  names(out) <- rownames(x)
  out
}

#' @rdname as_lol
#' @export

is_lol <- function(x) {
  is_simple_list(x) && all(map_lgl(x, is_simple_list))
}

#' @rdname as_lol
#' @export

is_lov <- function(x) {
  is_simple_list(x) && all(map_lgl(x, is_simple_vector))
}


#' List and count all the variables in lists within list
#'
#' @param x a list.
#'
#' @examples
#'
#' list_variables(as_lol(mtcars))
#'
#' @export

list_variables <- function(x) {
  if (!is_lol(x) && !is_lov(x))
    stop("x is neither list-of-lists, nor listo-f-vectors")
  table(unlist(lapply(x, names)))
}
twolodzko/lolplyr documentation built on May 14, 2019, 8:22 a.m.