R/import_pam_meta.R

Defines functions type_translate import_pam_meta

#!/usr/bin/Rscript
# -*- coding: utf-8 -*-

################################ Description ###################################
# Title: Import PAM metadata
# Purpose: Import PAM specific metadata
# Created the 2015-02-24 
# by Joris Muller
# Licence: GPLv3 <http://www.gnu.org/licenses/>
################################################################################



#' @title type_translate
#' @description Translate the "type" of a variable to a R type.
#' @param x character A character vector with types
#' @param rep_dict character Replacement dictionnary, in a vector form. The name of an element will replace the value of this element
#' @return A character vector with the type translated
#' @author Joris Muller 2015-02-24
#' @export

type_translate <- function(x, rep_dict) {
    
    new_types <- character()

    for (one in x) {
        if (one %in% names(rep_dict)) {
            new_type <- (rep_dict[names(rep_dict) == one])
        } else {
            new_type <- "not_used"
        }
        new_types <- c(new_types, new_type)
    } 

    return(new_types)
} # End of function "type_translate" definition
#' @title import_pam_meta
#' @description Import PAM metadata. This kind of metadata files consist in two data.frames: one to describe the variable, an other one to describe the factors (levels and labels)
#' @param tvar data.frame A data.frame with the columns nom_var, type, nom_court
#' @param tmod A data.frame with the columns nom_var, nom_modalite, libelle
#' @return A \code{database_def} object.
#' @author Joris Muller 2015-02-24
#' @export

import_pam_meta <- function(tvar, tmod) {
    
    
    lines <- seq_len(nrow(tvar))

    # Initialize a list to store the VariableDef
    list_descvar <- list()
    
    type_dictionnary <- c(
        "id" = "character",
        "quali" = "factor",
        "quali_ord" = "ordered",
        "quanti_cont" = "numeric",
        "binaire" = "factor",
        "quanti_disc" = "numeric"
        )

    for (i in lines) {
      
      # Get the line as a character vector
      a_line <- tvar[i,, drop = T]
      
      # Get the levels and labels of the factors
      
      levels_raw <- tmod[tmod$nom_var == a_line$nom_var, "nom_modalite"]

      if (length(levels_raw) == 0) 
      list_descvar <- append(
          list_descvar,
          # Create a new VariableDef object 
          vardef(
              rname = a_line$nom_var, 
              type = type_translate(a_line$type, type_dictionnary),
              varlabel = a_line$nom_court, 
              comment = a_line$nom_long, 
              levels =  , 
              names = tmod[tmod$nom_var == a_line$nom_var, "libelle"],
              originalname = a_line$nom_var
              )
          )
    }

    return(invisible(NULL))
} # End of function "import_pam_meta" definition
jomuller/vartors documentation built on May 19, 2019, 7:26 p.m.