Scripts relacionados con el acceso y análisis en bases de datos Access.
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.

580 lines
20 KiB

  1. ---
  2. title: "sqlFunctions-Doc"
  3. output:
  4. html_document:
  5. toc: true
  6. toc_depth: 2
  7. ---
  8. ```{r setup, include=FALSE}
  9. knitr::opts_chunk$set(echo = TRUE)
  10. ```
  11. ---
  12. ## sqlDropLast
  13. ### Description
  14. Removes from Database the last (or the amount specified) entry.
  15. ### Usage
  16. sqlDropLast(conn, tablename, droplast=1, dbtype=NULL)
  17. ### Arguments
  18. Argument|Description
  19. ---|---
  20. conn|connection handle returned by odbcConnect.
  21. tablename|character: a database table name accessible from the connected DSN.
  22. droplast|the amount of lines to be removed from the table strating from tail. By default, it removes only 1 line.
  23. dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
  24. ### Details
  25. Removes from Database the last (or the amount specified) entry.
  26. ### Value
  27. Invisibly for success (and failures cause errors).
  28. ### Examples
  29. ```r
  30. dta<-odbcConnect("test")
  31. sqlDropLast(dta, "TableTest")
  32. ```
  33. ### Function
  34. ```r
  35. sqlDropLast<-function(conn, tablename, droplast=1,dbtype=NULL){
  36. if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  37. if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  38. table<-sqlFetch(conn, tablename)
  39. table<-table[1:(nrow(table)-droplast),]
  40. if (dbtype == "OV"){sqlSave(conn, table, tablename = tablename, safer = F)}
  41. if (dbtype == "UM"){
  42. sqlDrop(conn, tablename)
  43. sqlSave(conn, table, tablename = tablename, safer = F)}
  44. }
  45. ```
  46. ---
  47. ## sqlInitizalize
  48. ### Description
  49. Loads required libraries and gets the db location.
  50. ### Usage
  51. sqlInitialize()
  52. ### Arguments
  53. Argument|Description
  54. ---|---
  55. ### Details
  56. Loads required libraries and gets the db location from "ruta_database.R" file.
  57. ### Value
  58. Invisibly for success (and failures cause errors).
  59. ### Examples
  60. ```r
  61. sqlInitialize()
  62. ```
  63. ### Function
  64. ```r
  65. sqlInitialize<-function(){
  66. library(tidyverse)
  67. library(RODBC)
  68. library(openxlsx)
  69. ## Conexión a la base de datos
  70. source("ruta_database.R", encoding = "UTF-8")
  71. }
  72. ```
  73. ---
  74. ## sqlBackUp
  75. ### Description
  76. Creates a Back Up copy of the database.
  77. ### Usage
  78. sqlBackUp(dbfile=file,conn=dta,bu.dir=NULL)
  79. ### Arguments
  80. Argument|Description
  81. ---|---
  82. dbfile| Database File location.
  83. conn|connection handle returned by odbcConnect.
  84. bu.dir|Directory under the DB file where the back up will be placed. It defaults to NULL and is deduced from conn database.
  85. ### Details
  86. Creates a Back Up copy of the database. It adds the date in front of the back up file.
  87. ### Value
  88. Invisibly for success (and failures cause errors).
  89. ### Examples
  90. ```r
  91. sqlInitialize()
  92. sqlBackUp()
  93. ```
  94. ### Function
  95. ```r
  96. sqlBackUp<-function(dbfile=file,conn=dta,bu.dir=NULL){
  97. if(sqlTables(conn) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){bu.dir<-"BU_UM"}
  98. if(sqlTables(conn) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"BU_OVARIO"}
  99. db=strsplit(dbfile, "/")[[1]]%>% tail(n=1)
  100. bu_path<-gsub(db,bu.dir,dbfile)
  101. if (!dir.exists(bu_path)){
  102. dir.create(bu_path)
  103. print(paste0("Back Up directory ", bu_path, " created"))
  104. }
  105. cp_bu<-paste0(bu_path, "/", format(Sys.time(), format="%Y%m%d"),"-",db)
  106. file.copy(dbfile, cp_bu)
  107. }
  108. ```
  109. ---
  110. ## sqlShowSamples
  111. ### Description
  112. Shows if there are already samples from the specified NHCs.
  113. ### Usage
  114. sqlShowSamples(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL)
  115. ### Arguments
  116. Argument|Description
  117. ---|---
  118. conn|connection handle returned by odbcConnect.
  119. nhcs|Character vector with the NHCs to test.
  120. verb|Verbose: if TRUE, all the columns from "SAMPLES" table are printed.
  121. dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
  122. ### Details
  123. Takes the NHCs listed in the nhcs vector and checks if there are already samples from those patients.
  124. ### Value
  125. A data.frame with information about the patients.
  126. ### Examples
  127. ```r
  128. dta<-odbcConnect("test")
  129. nhc.test<-c("XXXXXXXX","XXXXXXX")
  130. sqlShowSamples()
  131. ```
  132. ### Function
  133. ```r
  134. sqlShowSamples<-function(conn=dta, nhcs=nhc.test, verb=F, dbtype=NULL){
  135. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  136. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  137. if (dbtype == "OV"){
  138. db<-c("dbtables"="SAMPLES", "dbcode"="OVID", "dbsamples"="samples")
  139. query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
  140. }
  141. if (dbtype == "UM"){
  142. db<-c("dbtables"="MUESTRAS", "dbcode"="UMID", "dbsamples"="CODIGO")
  143. query<-paste0("SELECT O.NHC,S.* FROM ",db["dbtables"]," S INNER JOIN ",db["dbcode"]," O ON O.",db["dbcode"],"=S.",db["dbcode"])
  144. }
  145. if (nrow(sqlQuery(conn, query) %>% filter(NHC %in% nhcs)) == 0){
  146. return("No hay muestras de ningún paciente.")
  147. }
  148. if (isFALSE(verb)){
  149. sqlQuery(conn, query) %>% filter(NHC %in% nhcs) %>%
  150. group_by(NHC,UQ(rlang::sym(db["dbcode"]))) %>% summarise(Samples=length(UQ(rlang::sym(db["dbsamples"]))), Names=paste0(UQ(rlang::sym(db["dbsamples"])), collapse = ";")) %>%
  151. merge(data.frame(NHC=nhcs),all=T) %>% mutate(NHC=factor(NHC,levels = nhcs)) %>% arrange(NHC)
  152. }else{
  153. sqlQuery(conn, query) %>% filter(NHC %in% nhcs)
  154. }
  155. }
  156. ```
  157. ---
  158. ## sqlGenOVID
  159. ### Description
  160. Generates new consecutive OVID or UMID code for the patients that are not found in the DB.
  161. ### Usage
  162. sqlGenOVID(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL)
  163. ### Arguments
  164. Argument|Description
  165. ---|---
  166. conn|connection handle returned by odbcConnect.
  167. nhcs|Character vector with the NHCs to test.
  168. verb|Verbose: if TRUE (default), it prints the data.frame with the generated OVID codes.
  169. sinc|If TRUE (default is FALSE for security), it adds the new entries to the "OVID" table in the DB.
  170. dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
  171. ### Details
  172. Generates new consecutive OVID or UMID code for the patients that are not found in the DB.
  173. ### Value
  174. If verb is TRUE, it returns a data.frame.
  175. ### Examples
  176. ```r
  177. dta<-odbcConnect("test")
  178. nhc.test<-c("XXXXXXXX","XXXXXXX")
  179. sqlGenOVID(sinc=T)
  180. ```
  181. ### Function
  182. ```r
  183. sqlGenOVID<-function(conn=dta, nhcs=nhc.test, verb=T, sinc=F, dbtype=NULL){
  184. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  185. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  186. if (dbtype == "OV"){
  187. db<-c("dbcode"="OVID")
  188. }
  189. if (dbtype == "UM"){
  190. db<-c("dbcode"="UMID")
  191. }
  192. dbid<-sqlFetch(conn,db["dbcode"])
  193. new.nhc<-nhcs[!nhcs %in% dbid$NHC]
  194. next.num<-gsub(db["dbcode"],"",dbid[,db["dbcode"]]) %>% as.numeric %>% max(na.rm=T)+1
  195. last.num<-next.num+(length(new.nhc)-1)
  196. newtab<-data.frame("NHC"=new.nhc, "ID"=sprintf("%s%04d",db["dbcode"],next.num:last.num)) %>% rename(!!db["dbcode"]:="ID")
  197. if(dbtype=="OV"){
  198. dbid<-rbind(dbid,newtab)
  199. }
  200. if(dbtype=="UM"){
  201. dbid<-merge(dbid, newtab, all=T) %>% select(Id,NHC,UMID) %>% arrange(Id)
  202. dbid$Id<-as.numeric(rownames(dbid))
  203. dbid$NHC<-as.numeric(dbid$NHC)
  204. }
  205. rownames(dbid)<-as.character(1:nrow(dbid))
  206. dbid<-filter(dbid, NHC %in% new.nhc) %>% mutate(NHC=as.character(NHC))
  207. if (sinc){
  208. ### !! Atención, esto cambia la base de datos:
  209. sqlSave(conn, dbid, tablename=db["dbcode"], append = T)
  210. print("La base ha sido actualizada.")
  211. }
  212. if (verb){
  213. return(dbid)
  214. }
  215. }
  216. ```
  217. ---
  218. ## sqlWriteTemp
  219. ### Description
  220. Fills the Query Template file with the OVID or UMID and OV or UM newly generated codes.
  221. ### Usage
  222. sqlWriteTemp(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL)
  223. ### Arguments
  224. Argument|Description
  225. ---|---
  226. conn|connection handle returned by odbcConnect.
  227. nhcs|Character vector with the NHCs to test.
  228. file|Template file that will be used to interact with the DB.
  229. samples.mod|If TRUE (default), it fills the "samples" template sheet.
  230. clinics.mod|If TRUE (default), it fills the "CLINICS" template sheet.
  231. dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
  232. ### Details
  233. Fills the Query Template file with the OVID and OV or UMID and UM newly generated codes. It is required that the DB has been updated with the sqlGenOVID function. It replaces previous content in the template file sheets that are filled. In the case of "CLINICS" table, if there were already an entry in the DB for that OVID/UMID code, the template file is filled with that information.
  234. ### Value
  235. Invisibly for success (and failures cause errors).
  236. ### Examples
  237. ```r
  238. dta<-odbcConnect("test")
  239. nhc.test<-c("XXXXXXXX","XXXXXXX")
  240. sqlGenOVID(sinc=T)
  241. sqlWriteTemp()
  242. ```
  243. ### Function
  244. ```r
  245. sqlWriteTemp<-function(conn=dta, nhcs=nhc.test, file="queryOV.xlsx", samples.mod=T, clinics.mod=T, dbtype=NULL){
  246. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  247. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  248. if (dbtype=="OV"){
  249. upd.ovid<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  250. if (samples.mod){
  251. ## Generar código para las nuevas muestras
  252. samples<-sqlFetch(conn, "SAMPLES")
  253. if(sum(grepl(paste0("OV",Sys.time() %>% format("%y")), samples$samples)) > 0){
  254. next.samp<-gsub(paste0("OV",Sys.time() %>% format("%y")),"", samples$samples) %>% as.numeric %>% max(na.rm=T)+1
  255. }else{
  256. next.samp<-1
  257. }
  258. last.samp<-next.samp+(length(nhcs)-1)
  259. new.samp<-sprintf("OV%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  260. new.samp.df<-merge(sqlFetch(dta,"OVID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "samples"=new.samp))
  261. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(samples)
  262. }
  263. if (clinics.mod){
  264. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  265. upd.clinics<-sqlFetch(conn, "CLINICS")
  266. ovid.new<-sqlFetch(conn, "OVID") %>% filter(NHC %in% nhcs)
  267. upd.clinics<-merge(ovid.new,upd.clinics, all.x=T, by="OVID")
  268. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  269. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  270. }
  271. ## Exportar tablas a la plantilla de entrada para su rellenado
  272. wb <- loadWorkbook(file)
  273. writeData(wb, "NHC", upd.ovid)
  274. if (samples.mod){writeData(wb,"samples",samples.exp)}
  275. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  276. saveWorkbook(wb,file,overwrite = TRUE)
  277. }
  278. if (dbtype=="UM"){
  279. upd.umid<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
  280. if (samples.mod){
  281. ## Generar código para las nuevas muestras
  282. samples<-sqlFetch(conn, "MUESTRAS")
  283. if(sum(grepl(paste0("UM",Sys.time() %>% format("%y")), samples$CODIGO)) > 0){
  284. next.samp<-gsub(paste0("UM",Sys.time() %>% format("%y")),"", samples$CODIGO) %>% as.numeric %>% max(na.rm=T)+1
  285. }else{
  286. next.samp<-1
  287. }
  288. last.samp<-next.samp+(length(nhcs)-1)
  289. new.samp<-sprintf("UM%s%02d",Sys.time() %>% format("%y"),next.samp:last.samp)
  290. new.samp.df<-merge(sqlFetch(dta,"UMID") %>% merge(data.frame("NHC"=nhcs)), data.frame("NHC"=nhcs, "CODIGO"=new.samp))
  291. samples.exp<-merge(samples %>% slice(0), new.samp.df %>% select(-NHC), all=T) %>% select(colnames(samples)) %>% arrange(CODIGO)
  292. }
  293. if (clinics.mod){
  294. ## Importar los datos clínicos de pacientes existentes y generar nueva entrada par los nuevos
  295. upd.clinics<-sqlFetch(conn, "CLINICOS")
  296. umid.new<-sqlFetch(conn, "UMID") %>% filter(NHC %in% nhcs)
  297. upd.clinics<-merge(umid.new,upd.clinics %>% select(-Id), all.x=T, by="UMID")
  298. upd.clinics$NHC<-as.character(upd.clinics$NHC)
  299. for (i in colnames(upd.clinics)[sapply(upd.clinics, lubridate::is.POSIXct)]){upd.clinics[,i]<-as.Date(upd.clinics[,i])}
  300. }
  301. ## Exportar tablas a la plantilla de entrada para su rellenado
  302. wb <- loadWorkbook(file)
  303. writeData(wb, "NHC", upd.umid)
  304. if (samples.mod){writeData(wb,"samples",samples.exp)}
  305. if (clinics.mod){writeData(wb,"CLINICS",upd.clinics)}
  306. saveWorkbook(wb,file,overwrite = TRUE)
  307. }
  308. }
  309. ```
  310. ---
  311. ## sqlSincBD
  312. ### Description
  313. Updates the DB with the information filled in the template file.
  314. ### Usage
  315. sqlSincBD(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL)
  316. ### Arguments
  317. Argument|Description
  318. ---|---
  319. conn|connection handle returned by odbcConnect.
  320. filetemp|Template file that will be used to interact with the DB.
  321. sinc.samples|If TRUE (default is FALSE for security), it updates the SAMPLES table in the DB with the information in the "samples" template sheet.
  322. clinics.mod|If TRUE (default is FALSE for security), it updates the CLINICS table in the DB with the information in the "CLINICS" template sheet.
  323. dbtype|used to manually specify the database type. It defaults to NULL and the type is deduced.
  324. ### Details
  325. Updates the DB with the information filled in the template file. All the "samples" entries are added as new rows (as all samples are new even if the patient was already in the DB). The new patients included in the "CLINICS" sheet are introduced in the DB as new rows and the ones that were already there are modified in its previous row location.
  326. ### Value
  327. Invisibly for success (and failures cause errors).
  328. ### Examples
  329. ```r
  330. dta<-odbcConnect("test")
  331. nhc.test<-c("XXXXXXXX","XXXXXXX")
  332. sqlGenOVID(sinc=T)
  333. sqlWriteTemp()
  334. sqlSincBD(sinc.samples=T, sinc.clinics=T)
  335. ```
  336. ### Function
  337. ```r
  338. sqlSincBD<-function(conn=dta, filetemp="queryOV.xlsx", sinc.samples=F, sinc.clinics=F, dbtype=NULL){
  339. if(sqlTables(dta) %>% filter(TABLE_NAME == "UMID") %>% nrow > 0){dbtype<-"UM"}
  340. if(sqlTables(dta) %>% filter(TABLE_NAME == "OVID") %>% nrow > 0){dbtype<-"OV"}
  341. ## Añadir código de muestra nueva a la base de datos
  342. if (dbtype == "OV"){
  343. print("DB OV detectada")
  344. nsamples<-sqlFetch(conn, "SAMPLES") %>% nrow
  345. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  346. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  347. if (sinc.samples & nrow(upd.samples) > 0){
  348. upd.samples$IQ_date<-as.Date(upd.samples$IQ_date)
  349. upd.samples$TIL_date<-as.Date(upd.samples$TIL_date)
  350. ### !! Atención, esto cambia la base de datos:
  351. sqlSave(conn, upd.samples, tablename="SAMPLES", append = T, varTypes = c("IQ_date"="date","TIL_date"="date"))
  352. print("Tabla SAMPLES sincronizada.")
  353. }
  354. }
  355. if (dbtype == "UM"){
  356. print("DB UM detectada")
  357. nsamples<-sqlFetch(conn, "MUESTRAS") %>% nrow
  358. upd.samples<-read.xlsx(filetemp, sheet = "samples", detectDates = T)
  359. if (nrow(upd.samples) > 0){rownames(upd.samples)<-(nsamples+1):(nsamples+nrow(upd.samples)) %>% as.character}
  360. if (sinc.samples & nrow(upd.samples) > 0){
  361. upd.samples$FECHA_RECEPCION<-as.Date(upd.samples$FECHA_RECEPCION)
  362. upd.samples$TIPO<-as.character(upd.samples$TIPO)
  363. upd.samples$OBS<-as.character(upd.samples$OBS)
  364. ### !! Atención, esto cambia la base de datos:
  365. sqlSave(conn, upd.samples, tablename="MUESTRAS", append = T, varTypes = c("FECHA_RECEPCION"="Date"), rownames = F)
  366. print("Tabla MUESTRAS sincronizada.")
  367. }
  368. }
  369. ## Añadir datos clínicos modificados a la base de datos
  370. if (dbtype == "OV"){
  371. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  372. ovid.mod<-upd.clinics$OVID[upd.clinics$OVID %in% (sqlFetch(dta, "CLINICS") %>% pull(OVID))]
  373. rnames<-sqlFetch(conn, "CLINICS") %>% filter(OVID %in% ovid.mod) %>% rownames
  374. clinics.mod<-upd.clinics %>% filter(OVID %in% ovid.mod) %>% select(-NHC)
  375. rownames(clinics.mod)<-rnames
  376. ### !! Atención, esto cambia la base de datos:
  377. if (sinc.clinics){
  378. fechas<-colnames(clinics.mod)[grepl("DO|date", colnames(clinics.mod))]
  379. for (i in fechas){
  380. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  381. }
  382. sqlUpdate(conn, clinics.mod,"CLINICS")
  383. print("Tabla CLINICS modificada.")
  384. }
  385. }
  386. if (dbtype == "UM"){
  387. upd.clinics<-read.xlsx(filetemp, sheet = "CLINICS",detectDates = T)
  388. umid.mod<-upd.clinics$UMID[upd.clinics$UMID %in% (sqlFetch(dta, "CLINICOS") %>% pull(UMID))]
  389. rnames<-sqlFetch(conn, "CLINICOS") %>% filter(UMID %in% umid.mod) %>% rownames
  390. clinics.mod<-upd.clinics %>% filter(UMID %in% umid.mod) %>% select(-NHC)
  391. rownames(clinics.mod)<-rnames
  392. ### !! Atención, esto cambia la base de datos:
  393. if (sinc.clinics){
  394. fechas<-colnames(clinics.mod)[grepl("date|MET_DX|DoB", colnames(clinics.mod), ignore.case = T)]
  395. for (i in fechas){
  396. clinics.mod[,i]<-as.Date(clinics.mod[,i])
  397. }
  398. sqlUpdate(conn, clinics.mod,"CLINICOS")
  399. print("Tabla CLINICOS modificada.")
  400. }
  401. }
  402. ## Añadir datos clínicos nuevos a la base de datos
  403. if (dbtype == "OV"){
  404. nsamples.clin<-sqlFetch(conn, "CLINICS") %>% nrow
  405. ovid.new<-upd.clinics$OVID[!upd.clinics$OVID %in% (sqlFetch(conn, "CLINICS") %>% pull(OVID))]
  406. clinics.new<-upd.clinics %>% filter(OVID %in% ovid.new) %>% select(-NHC)
  407. if (length(ovid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  408. ### !! Atención, esto cambia la base de datos:
  409. if (sinc.clinics){
  410. fechas<-colnames(clinics.new)[grepl("DO|date", colnames(clinics.new))]
  411. varTypes<-rep("Date",length(fechas))
  412. names(varTypes)<-fechas
  413. for (i in fechas){
  414. clinics.new[,i]<-as.Date(clinics.new[,i])
  415. }
  416. sqlSave(conn, clinics.new, tablename="CLINICS", append = T, varTypes = varTypes)
  417. print("Tabla CLINICS sincronizada.")
  418. }
  419. }
  420. if (dbtype == "UM"){
  421. nsamples.clin<-sqlFetch(conn, "CLINICOS") %>% nrow
  422. umid.new<-upd.clinics$UMID[!upd.clinics$UMID %in% (sqlFetch(conn, "CLINICOS") %>% pull(UMID))]
  423. clinics.new<-upd.clinics %>% filter(UMID %in% umid.new) %>% select(-NHC)
  424. if (length(umid.new) > 0){rownames(clinics.new)<-(nsamples.clin+1):(nsamples.clin+nrow(clinics.new)) %>% as.character}
  425. ### !! Atención, esto cambia la base de datos:
  426. if (sinc.clinics){
  427. fechas<-colnames(clinics.new)[grepl("date|MET_DX|DoB", colnames(clinics.new), ignore.case = T)]
  428. varTypes<-rep("Date",length(fechas))
  429. names(varTypes)<-fechas
  430. for (i in fechas){
  431. clinics.new[,i]<-as.Date(clinics.new[,i])
  432. }
  433. sqlSave(conn, clinics.new, tablename="CLINICOS", append = T, varTypes = varTypes)
  434. print("Tabla CLINICOS sincronizada.")
  435. }
  436. }
  437. }
  438. ```
  439. ---
  440. ## sqlMultiSamples
  441. ### Description
  442. Prints a table compiling information about laboratory samples, scRNAseq samples and RNA/DNA samples.
  443. ### Usage
  444. sqlMultiSamples(kbl=F, NHC=F, full=F)
  445. ### Arguments
  446. Argument|Description
  447. ---|---
  448. kbl|formats the output table with the kableEstra style. Defaults to F.
  449. NHC|adds the NHC to the table in addition to the UMID. Defaults to F.
  450. full|prints also the patients that doesn't appear in the MUESTRAS table. Defaults to F.
  451. ### Details
  452. Prints a table compiling information about laboratory samples, scRNAseq samples and RNA/DNA samples.
  453. ### Value
  454. A data.frame or a kableExtra table.
  455. ### Examples
  456. ```r
  457. dta<-odbcConnect("test")
  458. sqlMultiSamples()
  459. ```
  460. ### Function
  461. ```r
  462. sqlMultiSamples<-function(kbl=F, NHC=F, full=F){
  463. query<-sqlQuery(dta, "SELECT U.UMID,U.NHC,M.FECHA_RECEPCION,M.TIPO,M.CODIGO,C.CODIGO,R.CODIGO,R.ESTADO
  464. FROM ((UMID U
  465. LEFT OUTER JOIN MUESTRAS M ON U.UMID=M.UMID)
  466. LEFT OUTER JOIN CNAG C ON M.CODIGO=C.CODIGO)
  467. LEFT OUTER JOIN RNADNA R ON M.CODIGO=R.CODIGO") %>% rename("CNAG"="CODIGO.1","RNADNA"="CODIGO.2")
  468. if (full==F){query<- query %>% filter(!is.na(CODIGO))}
  469. if (NHC==F){query<- query %>% select(-NHC)}
  470. query<-query %>% mutate(
  471. CNAG=case_when(!is.na(CNAG)~"X",TRUE~""),
  472. RNADNA=case_when((!is.na(RNADNA) & (ESTADO=="ENV"))~"X",
  473. (!is.na(RNADNA) & (is.na(ESTADO)))~".",
  474. TRUE~"")
  475. ) %>% select(-ESTADO)
  476. if (kbl==T){
  477. query %>% kableExtra::kbl() %>% kableExtra::kable_styling(full_width = F, bootstrap_options = c("striped"))
  478. }else{
  479. return(query)
  480. }
  481. }
  482. ```