valid_variables_script.R 15.2 KB
Newer Older
1 2
rm(list=ls())

3
dir_name <- readline("Introduce the name of the directory please: ")
4

5
setwd(dir_name)
6

7 8 9 10 11
source("dependency_installer.R")
source("connection_parameters.R")
source("necessary_functions_connection.R")
#source("required_folder_checker.R")
#source("argument_hasher.R")
12

13

14
dep_list = c("jsonlite", "stringr","DSI","DSOpal","DSLite", "fields", "metafor", "ggplot2", "gridExtra", "data.table", "dsBaseClient", "openxlsx")
15 16
install_dependencies(dep_list)

17
codebook_file <- "20220315_Data Harmonisation.xlsb.xlsx"
18

19 20
codebook_demo <- read.xlsx(codebook_file , sheet = 2 )
codebook_com_and_rf <- read.xlsx(codebook_file , sheet = 3 ) 
21

22 23
codebook_home_med <- read.xlsx(codebook_file , sheet = 4 ) 
codebook_si_sympt <- read.xlsx(codebook_file , sheet = 5 ) 
24

25 26
codebook_treatments <- read.xlsx(codebook_file , sheet = 6 ) 
codebook_labo <- read.xlsx(codebook_file , sheet = 7 ) 
27

28 29
codebook_complications <- read.xlsx(codebook_file , sheet = 8 ) 
codebook_imaging_data <- read.xlsx(codebook_file , sheet = 9 ) 
30

31 32
codebook_lifestyle_diet <- read.xlsx(codebook_file , sheet = 10 ) 
codebook_dates <- read.xlsx(codebook_file , sheet = 11 )
33

34 35 36 37 38 39 40
codebook <- rbind(codebook_demo , codebook_com_and_rf)
codebook <- rbind(codebook , codebook_home_med)
codebook <- rbind(codebook , codebook_si_sympt)
codebook <- rbind(codebook , codebook_treatments)
codebook <- rbind(codebook , codebook_labo)
codebook <- rbind(codebook , codebook_complications)
codebook <- rbind(codebook , codebook_imaging_data)
41

42 43 44
codebook_lifestyle_diet <- codebook_lifestyle_diet[, !names(codebook_lifestyle_diet) %in% c("X2", "X4" , "X10")] 
codebook <- rbind(codebook , codebook_lifestyle_diet)
codebook <- rbind(codebook , codebook_dates)
45

46

47 48 49
codebook_col_names <- as.data.frame(codebook$Harmonised.variable.name)

names(codebook_col_names) <- c("col_names")
50 51 52 53 54 55 56

categoric_vars = c("DMRGENDR", "DMRBORN", "DMRRETH1", "DMROCCU", "DMRHREDU", "DSXOS", "DSXHO", "DSXIC", "TRXAV","TRXRIB","TRXLR","TRXRM","TRXIA","TRXIB","TRXCH","TRXAB","TRXCS","TRXHEP","TRXAF","TRXCP","TRXOT","TRXECM","TRXIV","TRXNIV","TRXNO","TRXOX","TRXRR","TRXTR","TRXVA","TRXPE","TRXPV","TRXIT","TRXNMB","TRXAC","TRXINA","TRXIS","TRXIM","TRXVC","TRXVD","TRXZN",                         "CSXCOT","CSXCTR","SMXASAH","SMXFEA","SMXCOA","SMXSTA","SMXSBA","SMXRNA","SMXMYA","SMXARA","SMXCPA","SMXAPA","SMXINA","SMXNAA","SMXDIA","SMXFAA","SMXHEA","SMXCNA","SMXACA","SMXSLA","SMXTLA","SMXSYA","SMXWHA","SMXLYA","SMXANA","SMXIWA","SMXSRA","SMXBLA","CMXPRG","CMXCVD","CMXCMP","CMXHT","CMXDI","CMXCKD","CMXCLD","CMXCPD","CMXASM","CMXCND","CMXRHE","CMXCCI","CMXCBD","CMXDE","CMXPU","CMXST","CMXLY","CMXAP","RFXSM","RFXFSM","RFXOB","RFXTB","RFXIMD","RFXHIV","RFXAIDS","RFXUI","RFXHC","RFXONC","RFXMN",                         "HMRACI","HMRARB","HMRAHO","HMRNS","HMROS","HMRCS","HMRIS","HMRAV","HMRAB","HMRCOV","IMDXCT","IMDXCTCR","IMDXCTTE","IMDXCTAB","IMDXXR","IMDXPN",                         "COXRD","COXAR","COXPM","COXMOD","COXPT","COXEC","COXSH","COXIO","COXPE","COXST","COXDIC","COXRIO","COXKF","COXHF","COXBC")


#----------------------------------------------------------------------------

#Test if column names are valid
57
check_column_names <- function(codebook_param, colnames){
58 59
  
  str_res <- "The column names:"
60 61 62 63 64 65 66 67 68
  valid_colnames <- c()
  
  for(i in 1:(nrow(colnames))){
    colname <- colnames[i,1]
    number_of_column <- check_valid_name(colname ,  colnames) 
    if(number_of_column != 1){
      str_res<- paste(str_res, colname, sep=" ")
    }else{
      valid_colnames <- c(valid_colnames, colname)
69 70 71 72 73
    }
  }
  
  str_res<- paste(str_res,"are not registered in the harmonized data codebook \n", sep=" ")
  
74
  result <- list("not_colnames" = str_res , "colnames" = valid_colnames)
75
  
76
  return (result)
77 78 79
}

#Test if a single variable name is valid
80
check_valid_name <- function(col_name , col_names){
81
  
82
  valid <- 0
83
  
84 85 86 87
  if(col_name %in% codebook_col_names$col_names){
    
    valid <- length(grep(col_name, col_names))
    
88 89
  }
  
90
  return (valid)
91 92 93
  
}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
remove_space <- function(x){
  searchString <- ' '
  replacementString <- ''
  res = sub(searchString,replacementString,x)
  return(res)
}

remove_spaces_from_ds <- function(ds){
  
  res<- lapply(ds,remove_space )
  
  return(as.data.frame(res))
  
}

is_number <- function(x){
  res <- FALSE
  
  
  if(length(x)!=0){
    x <- str_replace(x,",",".")
    
    aux <- as.numeric(x)
117
    
118 119 120 121 122 123 124 125 126 127
    
    if(!is.na(aux))
      res <- TRUE
  }
  
  
  return(res)
  
}

128
check_values_not_categoric <- function(values, colname , codebook_param){
129 130 131
  
  valid_vals <- values
  
132
  possible_vals <- possible_values(colname, codebook_param)
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
  
  for(i in  1:length(values)){
    
    res<- FALSE
    
    value <- values[[i]]
    
    if(is_number(value)){
      value <- str_replace(value,",",".")
      value <- as.numeric(value)
    }
    
    if(is.null(value)){
      res <- TRUE
    }
148
    
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    else if( value == "NA" | value == "nan" | value == ".")
      res <- TRUE
    else{
      
      if(nrow(possible_vals) == 2 & (!grepl("DAT",colname, fixed=TRUE)) & colname !="CSXCTR"){
        
        if(colname=="LBXBEH" | colname=="LBXBEHn" | colname=="LBXBEM"){
          lower = possible_vals[1,1][[1]]
          higher = possible_vals[2,1][[1]]
          
        }else{
          bounds <- as.data.frame(strsplit(possible_vals[1,1], '-'))
          lowerAux <- str_replace(bounds [1,1],",",".")
          higherAux <- str_replace(bounds [2,1],",",".")
          lower <- as.numeric(remove_space(lowerAux))
          higher <- as.numeric(remove_space(higherAux))
        }
        
        
        if ((value >= lower & value <= higher))
          res <- TRUE
      }
      
      if(nrow(possible_vals) == 3 | colname=="CSXCTR"){
        if(value == 0 | value == 1)
          res <- TRUE
      }
      
      if(nrow(possible_vals) > 3){
        
        lower <- strtoi(remove_space(possible_vals[1,1]))
        higher_b <- nrow(possible_vals)-1
        higher <- strtoi(remove_space(possible_vals[higher_b,1]))
        
        if ((value >= lower & value <= higher))
          res <- TRUE
      }
    }
    
    if(res == FALSE)
      valid_vals[i] <- res
    
    
  }
  
  return(valid_vals)
}

197
possible_values <- function(colname , codebook_param){
198
  
199
  if(colname=="LBXBEH" | colname=="LBXBEHn" | colname=="LBXBEM")
200 201 202 203
    res <- t(as.data.frame(list(-20,20)))
  
  else{
    
204 205
    possible_value <- subset(codebook_param,codebook_param$Harmonised.variable.name==colname)[1,5]
    res <- strsplit(possible_value,split="/")
206 207 208 209 210
  }
  
  return(as.data.frame(res))
}

211
possible_values_categoric <- function(codebook_param){
212
  
213
  possible_value <- subset(harmonised_data,harmonised_data$Harmonised.variable.name==x)[1,4]
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
  res <- strsplit(x=possible_value,split="/")
  
  return(as.data.frame(res))
}

check_values_categoric <- function(values, colname){
  
  possible_vals <- possible_values_categoric(colname)
  
  res <- TRUE
  
  for(i in 1:length(values)){
    if(!(values[[i]] %in% as.matrix(remove_spaces_from_ds(possible_vals)))){
      res <- FALSE
    }
    
  }
  
  return(res)
  
}


get_values_from_quantiles <- function(x){
  
239
  data_summary <- ds.summary(x)
240
  
241
  low_quantile <- data_summary$HM$`quantiles & mean`[[1]]
242
  
243
  high_quantile <- data_summary$HM$`quantiles & mean`[[7]]
244 245 246 247 248 249
  
  return(list(low_quantile,high_quantile))
  
  
}

250
notify_error <- function(invalid_name_list,invalid_value_list,wrong_categoric, wrong_categoric_values, missing_numeric, codebook_param){
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  
  res <- ""
  
  if(length(invalid_name_list) !=0){
    res <- "There are invalid values in the numeric fields:"
    
    
    for(i in 1:length(invalid_name_list)){
      res <- paste(res, invalid_name_list[i], sep=" ")
    }
    
    res <- paste(res, "\n", sep="")
    
    for(i in 1:length(invalid_name_list)){
      res <- paste(res, error_message(invalid_name_list[i], invalid_value_list[[i]]), sep=" ")
    }
  }
  
  
  if(length(wrong_categoric)!=0){
    
    res <- paste(res, "\n############################################################################ \n", sep="")
    
    res <- paste(res,"\nThe following categoric values are invalid:", sep=" ")
    
    for(i in 1:length(wrong_categoric)){
      res <- paste(res, wrong_categoric[i], sep=" ")
    }
    
    res <- paste(res, "\n", sep="")
    
    for(i in 1:length(wrong_categoric)){
283
      res <- paste(res, error_message_categoric(wrong_categoric[i], wrong_categoric_values[[i]], codebook_param), sep=" ")
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    }
  }
  
  if(length(missing_numeric)!=0){
    
    res <- paste(res, "\n############################################################################ \n", sep="")
    
    res<- paste(res, "\nThe following fields are missing a numeric field:")
    
    for(i in 1:length(wrong_categoric)){
      res <- paste(res, missing_numeric[i], sep=" ")
    }
  }
  
  res <- paste(res, "\n", sep="")
  
  
  return(res)
  
}

305
error_message_categoric <- function(colname, invalid_values, codebook_param){
306 307 308 309 310
  
  res<- "\nValues in the field"
  res<- paste(res, colname, sep=" ")
  res<- paste(res, "should be", sep=" ")
  
311
  range <- possible_values_categoric(colname , codebook_param)
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
  
  for(i in 1:nrow(range)){
    res <- paste(res, remove_space(range[i,1]), sep=" ")
  }
  
  
  res<- paste(res, "\nBut values were:", sep=" ")
  
  for(j in 1:length(invalid_values)){
    res<- paste(res, invalid_values[[j]], sep=" ")
  }
  
  res<- paste(res, "\n\n", sep="")
  
  
  return(res)
  
}

error_message <- function(colname, invalid_values){
  
  res<- "\nValues in the field"
  res<- paste(res, colname, sep=" ")
  res<- paste(res, "should be", sep=" ")
  
  if(grepl("numeric", colname,fixed=TRUE))
    new_colname <- strsplit(x=colname,split="_")[[1]][1]
  else
    new_colname <- colname
  
342
  range <- subset(harmonised_data, harmonised_data$Harmonised.variable.name == new_colname)
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  range <- range[5]
  range <- as.data.frame(strsplit(range[1,1], '/'))
  
  #Range of values or null
  if(nrow(range) == 2 & !grepl("DAT",colname, fixed=TRUE)){
    bounds <- as.data.frame(strsplit(range[1,1], '-'))
    lower <- remove_space(bounds [1,1])
    higher <- remove_space(bounds [2,1])
    res<- paste(res, "numbers between", sep=" ")
    res<- paste(res, lower, sep=" ")
    res<- paste(res, "and", sep=" ")
    res<- paste(res, higher, sep=" ")
    res<- paste(res, "(both included)", sep=" ")
  }
  
  if(nrow(range) == 3){
    res<- paste(res, "0 or 1", sep=" ")
  }
  
  if(nrow(range) > 3){
    lower <- strtoi(remove_space(range[1,1]))
    higher_b <- nrow(range)-1
    higher <- strtoi(remove_space(range[higher_b,1]))
    res<- paste(res, "numbers between", sep=" ")
    res<- paste(res, lower, sep=" ")
    res<- paste(res, "and", sep=" ")
    res<- paste(res, higher, sep=" ")
    res<- paste(res, "(both included)", sep=" ")
  }
  
  if(grepl("DAT",colname, fixed=TRUE)){
    res<- paste(res, "dates with the following format: dd/mm/yyyy", sep=" ")
  }
  
  
  res<- paste(res, "\nBut values were:", sep=" ")
  
  for(j in 1:length(invalid_values)){
    res<- paste(res, invalid_values[[j]], sep=" ")
  }
  
  res<- paste(res, "\n", sep="")
  
  if(!is_number(invalid_values[[1]]))
    res<- paste(res, "(It's missing a \"numeric\" field)", sep="")
  
  res<- paste(res, "\n", sep="")
  
  return(res)
  
}

395
check_valid_values <- function(valid_colnames , codebook_param){
396 397 398 399 400 401 402 403 404 405 406
  
  invalid_name_list <- c()
  cannot_analyse_list <- c()
  invalid_values_list <- list()
  wrong_categoric_values <- list()
  wrong_categoric <- c()
  missing_numeric <- c()
  j<- 1
  k <- 1
  
  for(i in  1:(nrow(valid_colnames))){
407
    
408
    data_available <- FALSE
409 410
    data_table <- "empty"
    colname <- valid_colnames[i, 1]
411
    
412 413 414
    if(grepl("DMRBORN",colname, fixed=TRUE) | (grepl("DAT",colname, fixed=TRUE)) | (grepl("ISO",colname, fixed=TRUE)) | (grepl("BEF", colname, fixed=TRUE))){
      next 
    }
415
    
416 417 418 419 420
    column <- "data$"
    column <- paste(column, colname, sep="")
    
    tryCatch(
      error = function(cnd) {
421
        print(paste("Unable to analyse data" , cnd , sep = " "))
422 423
        res <- FALSE
      },
424
      {
425
      data_table <- as.data.frame(ds.table(column))
426 427
      data_available <- TRUE
      }
428 429
    )
    
430
    if(data_available){
431
      
432
      cannot_analyse_list <- c(cannot_analyse_list, colname)
433
      
434
    }else{
435
      
436 437 438 439 440 441 442 443 444 445 446
      
      if (data_table[[1]] == "All studies failed for reasons identified below")
        values <- get_values_from_quantiles(column)
      else
        values <- row.names(data_table)
      
      numeric_col<- paste(colname,"_numeric", sep="")
      
      if( colname %in% categoric_vars ){
     
        has_numeric <-  numeric_col %in% valid_colnames$`valid_data_colnames(data_colnames)`
447
        
448 449
        if(!has_numeric)
          missing_numeric <- c(missing_numeric, colname)
450 451
        
        
452
        if (data_table[[1]] == "All studies failed for reasons identified below"){
453
          
454
          cannot_analyse_list <- c(cannot_analyse_list,colname)
455
          
456
        }else  if(!check_values_categoric(values,colname)){
457
          
458 459
          print("Wrong categoric value:")
          print(colname)
460
          
461 462 463 464 465 466 467 468 469 470 471 472
          wrong_categoric <- c(wrong_categoric, colname)
          wrong_categoric_values[[k]] <- values
          k <- k+1
        }
        
      }else{
        
        if(grepl("numeric", colname,fixed=TRUE))
          new_colname <- strsplit(x=colname,split="_")[[1]][1]
        else
          new_colname <- colname
        
473
        valid <- check_values_not_categoric(values, new_colname , codebook_param)
474 475 476 477 478 479 480 481 482 483 484 485 486
        
        if (FALSE %in% valid){
          invalid_name_list <- c(invalid_name_list,colname)
          invalid_values_list[[j]] <- values
          j <- j+1
        }
        
        
        #print(colname)
        #print(values)
        
      }#else
      # print("This variable has a numeric version")
487
    }
488
    
489 490 491 492
  }
  
  missing_numeric
  if(length(invalid_name_list)>0 | length(wrong_categoric)>0 | length(missing_numeric)>0){
493
    res <- notify_error(invalid_name_list, invalid_values_list, wrong_categoric, wrong_categoric_values, missing_numeric, codebook_param)
494 495 496 497 498 499 500 501 502
  }else{
    res <- "All values are valid \n"
  }
  
  if(length(cannot_analyse_list)>0){
    res <- paste(res, "\n############################################################################ \n", sep="")
    
    res <- paste(res, notify_unable_analyse(cannot_analyse_list), sep="\n" )
  }
503
  
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
  
  
  
  return(res)
  
}

notify_unable_analyse <- function(x){
  
  res <- "\nCould not obtain data from the fields:"
  
  for(i in 1:length(x)){
    res <- paste(res, x[i], sep=" ")
  }
  
  return (res)
  
  
}

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
auxConnections <- connect()
connections <- auxConnections[[1]]
inp <- auxConnections[[2]]

#Conexión a la base de datos

ds.dim("data", datasources = connections)
ds.colnames("data")

#----------------------------------------------------------------------------

#Check valid column names
datastructure_name <- "data"
data_colnames <- ds.colnames(x=datastructure_name, datasources= connections)

data_colnames <- as.data.frame(data_colnames)
540

541 542
check_valid_columns <- check_column_names(codebook ,data_colnames)
valid_columns <- as.data.frame(check_valid_columns$colnames)
543 544 545


result <- ""
546
result<-check_valid_values(valid_columns, codebook)
547
print(check_valid_columns)
548
datashield.logout(connections) 
549 550 551 552 553 554 555
cat(result)

file_name<- paste(hospital_name,"_invalid_values.txt", sep="")

dir.create("../invalid_values", showWarnings = FALSE)
setwd("../invalid_values")

556

557 558 559
cat(check_valid_columns,file=file_name,sep="\n")
cat(result,file=file_name,append=TRUE)

560
datashield.logout(connections) 
561

562