You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

181 lines
6.7KB

  1. #' Charger un fichier de donnees dans l'environnement
  2. #'
  3. #' Charge un fichier texte ou excel contenant les donnees ainsi que les formats et labels
  4. #'
  5. #' La fonction charge les donnees contenues dans le fichier de donnees et renvoie une table de valeurs.
  6. #' Si des labels/formats sont definis ils seront appliques (fichiers labels.sas, formats.sas et attribformats.sas)
  7. #' Les variables pour lesquelles un format est defini seront considerees comme des variables qualitatives.
  8. #' La table de valeurs prend automatiquement le nom du fichier (suffixe par le numero de feuille).
  9. #' Le fichier de donnees est charge depuis ../../data/, les formats depuis le repertoire courant.
  10. #' @encoding UTF-8
  11. #' @param fichier Fichier de donnees a charger
  12. #' @param feuille Feuille a utiliser si fichier excel et en cas de feuilles mutiples (et qu'on veut acceder a une feuille au-dela de la premiere)
  13. #' @param chemin Chemin ou trouver le fichier de donnees (par defaut ../../data/)
  14. #' @return La data frame avec les labels et formats
  15. #' @examples
  16. #' \dontrun{Ma_table <- charger("donnees.xls", feuille=2)}
  17. #' @export
  18. charger <- function(fichier,feuille=1,chemin="../../data/")
  19. {
  20. # Verification de la presence du fichier
  21. fichier<-paste(chemin,fichier,sep="")
  22. if (!file.exists(fichier))
  23. {
  24. warning("Le fichier source n'existe pas !")
  25. return -1
  26. }
  27. # Lecture du fichier selon l'extension
  28. if (grepl("\\.csv$",fichier) || grepl("\\.txt$",fichier))
  29. x<-read.csv2(fichier, na.strings="",encoding="native.enc")
  30. else if (grepl("\\.xlsx?$",fichier))
  31. x<-read.xlsx(fichier,feuille,encoding="native.enc")
  32. # Lecture des formats a partir du fichier SAS
  33. x <- loadFormatsFromFile(x, "formats.sas", "attribformats.sas")
  34. # Lecture des labels a partir du fichier SAS
  35. x <- loadLabelsFromFile(x,"labels.sas")
  36. return(x)
  37. }
  38. #' Load labels from a flat file
  39. #'
  40. #' Loads label values from a flat file and applies them to the provided dataframe
  41. #'
  42. #' This function takes a dataframe and adds label attributes to the variables.
  43. #' The file must be formatted like so :
  44. #' variablename = "Label for the variable"
  45. #' with one line per variable
  46. #' As always, be careful of the case sensitiveness and the use of double quotes !
  47. #' @encoding UTF-8
  48. #' @param dataframe The dataframe to which you want to assign labels
  49. #' @param file The flat file from which to load the label data
  50. #' @return The dataframe with label attributes
  51. #' @examples
  52. #' \dontrun{df <- loadLabelsFromFile(df,"labels.txt")}
  53. #' @export
  54. loadLabelsFromFile <- function(dataframe, file)
  55. {
  56. if (missing(dataframe) | missing(file))
  57. {
  58. warning("Dataframe or file missing")
  59. return -1
  60. }
  61. if (!file.exists(file))
  62. {
  63. warning("File doesn't exists")
  64. return -1
  65. }
  66. con=file(file,"r",encoding="native.enc")
  67. labelsfile=readLines(con)
  68. close(con)
  69. labels=labelsfile[grepl('^ *\\w*?[[:space:]]*=[[:space:]]*\\".*?\\" *$',labelsfile)]
  70. labels=paste(labels,collapse=",")
  71. label_exe = paste("label(dataframe)<-c(",labels,")")
  72. eval(parse(text=label_exe))
  73. dataframe
  74. }
  75. #' Load formats from flat files
  76. #'
  77. #' Loads factor levels from flat files and applies them to the provided dataframe
  78. #'
  79. #' This function takes a dataframe and assigns factor levels to the corresponding variables.
  80. #' Two files must be provided :
  81. #' One describing the formats to be used (permitting the re-use of a defined format), which must be formatted like so:
  82. #' value format_name
  83. #' value0_in_data_frame = 'Label for level 0'
  84. #' value1_in_data_frame = "Label for level 1"
  85. #' and so on.
  86. #' As shown, both single and double quotes are accepted.
  87. #' The value before the equal sign can be numeric (categorical coding) or text for recoding.
  88. #' The other file assigns defined formats to variables in the dataframe. It must be formatted like so:
  89. #' var1 var2 var3 varN format=format_name
  90. #' with one line for every assigned format.
  91. #' As always, be careful of the case sensitiveness.
  92. #' @encoding UTF-8
  93. #' @param dataframe The dataframe to which you want to assign labels
  94. #' @param file The flat file from which to load the label data
  95. #' @return The dataframe with label attributes
  96. #' @examples
  97. #' \dontrun{df <- loadFormatsFromFile(df,"formats.txt","attribformats.txt")}
  98. #' @export
  99. loadFormatsFromFile <- function(dataframe, file_format, file_attrib)
  100. {
  101. if (missing(dataframe) | missing(file_format) | missing(file_attrib))
  102. {
  103. warning("Dataframe or file missing")
  104. return -1
  105. }
  106. if (!file.exists(file_format) | !file.exists(file_attrib))
  107. {
  108. warning("One of the files doesn't exist !")
  109. return -1
  110. }
  111. formats=list(0)
  112. con=file(file_format,"r",encoding="native.enc")
  113. formatsfile=readLines(con)
  114. close(con)
  115. # Nettoyage du fichier : espaces de debut et fin, et autour des '=', commentaires, conservation uniquement des lignes significatives (value xxx et 'code'='level')
  116. formatsfile=sub("^[[:space:]]*(.*?)[[:space:]]*$","\\1",formatsfile)
  117. formatsfile=sub("[[:space:]]*=[[:space:]]*","=",formatsfile)
  118. formatsfile=sub("/\\*.*?\\*/","",formatsfile)
  119. formatsfile=sub(";","",formatsfile)
  120. formatsfile=formatsfile[grepl("^value[[:space:]]*\\w",formatsfile) | grepl(".*?=(\\'|\").*?(\\'|\")",formatsfile)]
  121. formatsfile=sub("^(.*?)=","\\'\\1\\'=",formatsfile)
  122. # Creation de la liste de formats
  123. for (format in formatsfile)
  124. {
  125. if (grepl("^value *\\w",format))
  126. formats[[strsplit(format," ")[[1]][2]]]<-character(0)
  127. else
  128. eval(parse(text=paste0("formats[[length(formats)]]<-c(formats[[length(formats)]],",format,")")))
  129. }
  130. formats[[1]]<-NULL
  131. con=file(file_attrib,"r",encoding="native.enc")
  132. attribfile=readLines(con)
  133. close(con)
  134. # Nettoyage du fichier : espaces de debut et fin, espaces multiples, autour des '=', '.' final, conservation uniquement des lignes significatives (finissant en format=xxx)
  135. attribfile=sub("^[[:space:]]*(.*?)[[:space:]]*$","\\1",attribfile)
  136. attribfile=sub("\\.?$","",attribfile)
  137. attribfile=sub("/\\*.*?\\*/","",attribfile)
  138. attribfile=sub(";","",attribfile)
  139. attribfile=sub("[[:space:]]*=[[:space:]]*","=",attribfile)
  140. attribfile=attribfile[grepl("(\\w[[:space:]]+)+format=\\w",attribfile)]
  141. attribfile=gsub("[[:space:]]+"," ",attribfile)
  142. # Attribution des formats aux variables concernees
  143. for (attrib in attribfile)
  144. {
  145. attrib=strsplit(attrib," ")[[1]]
  146. format=strsplit(attrib[length(attrib)],"=")[[1]][2]
  147. for (var in attrib[-length(attrib)])
  148. {
  149. if (!is.null(dataframe[[var]]))
  150. dataframe[[var]]<-factor(dataframe[[var]],levels=names(formats[[format]]),labels=formats[[format]])
  151. }
  152. }
  153. # Remplacement des "" par NA dans les facteurs
  154. for (var in names(dataframe))
  155. {
  156. if (is.factor(dataframe[[var]]))
  157. levels(dataframe[[var]])[levels(dataframe[[var]])==""]<-NA
  158. }
  159. dataframe
  160. }