R/flatten.R

#' @title Flatten a list of length one
#' @description Flatten a list of length one to data frame by respecting data types (lists of greater length might not work as expexted)
#' @param x list 
#' @return data.frame of input 
#' @export
#' @examples 
#' flatten(list(list(a = 1, b = list(c = "c", d = TRUE)), list(a = 1, b = list(c = "c", d = TRUE))))
#' flatten(list(a = list(b = list(c = list(d = 1, e = FALSE), g = "tata")) ))
#' # if there is multi length vector inside the list --> multiple lines
#' flatten(list(a = list(b = list(c = list(d = 1, e = FALSE), g = "tata"), h = 1:2) ))
#' # what if no name
#' flatten(list(1, 2, 3))
#' # partial names
#' flatten(list(1, 2, c = 3))
flatten <- function(x) {
  if(!is.list(x)) x <- as.list(x)
  len <- sum(rapply(x, function(x) 1L))
  name <- names(rapply(x, function(x) 1L))
  y <- vector('list', len)
  i <- 0L
  rapply(x, function(x) { i <<- i + 1L; y[[i]] <<- x })
  z <- as.data.frame(y, stringsAsFactors = F)
  names(z) <- gsub(pattern = ".", "_", name, fixed = T )
  return(z)
}
bhakyuz/sahibinden documentation built on June 12, 2019, 2:28 p.m.