R/makeDF_from_list_of_named_vectors.2.R

Defines functions makeDF_from_list_of_named_vectors.2

Documented in makeDF_from_list_of_named_vectors.2

#' Make data frame from list of named vector
#' 
#' In the output data frame row names are named after list names, while column names after unique vector names (if infer_column_names is TRUE)
#' 
#' @param lst List of named vectors which we want to position in the outputted data frame.
#' @param infer_count_of_columns Boolean. Should function infer the count of columns in output by taking the maximum length among vector lenghts? Defults to FALSE.
#' @param ncols Integer of count of columns if infer_count_of_columns set to FALSE. Defults to 4.
#' @param infer_column_names Boolean. Should function infer the names of columns by taking the unique names among amalgamation of vector names? Defults to FALSE.
#' @param colnames Character vector of column names if infer_column_names set to FALSE. Defults to c("home insurance","energy","council tax","water").
#' @return A data frame whose columns are refernceColumnNames while rows are the vector members of the lst. 
#' @author Alexander Kheirallah ([email protected])
#' @export


makeDF_from_list_of_named_vectors.2 = function(lst,infer_count_of_columns = F, ncols=4, infer_column_names = F, colnames = c("home insurance","energy","council tax","water")){
  # inferring column count or assuming thereof
  if(infer_count_of_columns){
    maxlen = max(sapply(lst, length))
  }
  else{
    maxlen = ncols
  }
  o = as.data.frame(matrix(nrow = 1, ncol = maxlen))
  # inferring unique column names or assuming thereof
  if(infer_column_names){
    refernceColumnNames = c()
    for(i in 1:length(lst)){
      refernceColumnNames = c(refernceColumnNames, names(lst[[i]]))
    }
    refernceColumnNames = unique(refernceColumnNames)
    refernceColumnNames = tolower(refernceColumnNames)
  }
  else{
    refernceColumnNames = tolower(colnames)
  }
  colnames(o) = refernceColumnNames
  # building the data frame
  for(i in 1:length(lst)){
    # if no costs data is available (only NA present) than insert NAs and leave iteration of loop
    if(is.na(lst[[i]]) & length(lst[[i]])==1){
      o = rbind(o,rep(NA,ncol(o)))
      next
    }
    names(lst[[i]]) = tolower(names(lst[[i]]))
    # identifying the locations to insert data points per correspndance between column names and vector (i.e. list member) names
    insertHere = match(names(lst[[i]]),colnames(o))
    o = rbind(o,rep(NA,ncol(o)))
    o[nrow(o),insertHere] = lst[[i]]
  }
  o = o[-1,]
  row.names(o) = names(lst)
  return(o)
}
msxakk89/dat documentation built on April 3, 2020, 5:39 p.m.