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

3
dir_name <- readline("Introduce the name of the directory please: ")
4
#/Users/gnl/Documents/CTB UPM/UNCOVER/uncover_harmonization
5

6
setwd(dir_name)
7

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

14

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

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

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

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

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

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

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

35 36 37 38 39 40 41
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)
42

43 44 45
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)
46

47

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

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

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
58
check_column_names <- function(codebook_param, colnames){
59 60
  
  str_res <- "The column names:"
61 62 63 64 65 66 67 68 69
  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)
70 71 72 73 74
    }
  }
  
  str_res<- paste(str_res,"are not registered in the harmonized data codebook \n", sep=" ")
  
75
  result <- list("not_colnames" = str_res , "colnames" = valid_colnames)
76
  
77
  return (result)
78 79 80
}

#Test if a single variable name is valid
81
check_valid_name <- function(col_name , col_names){
82
  
83
  valid <- 0
84
  
85 86 87 88
  if(col_name %in% codebook_col_names$col_names){
    
    valid <- length(grep(col_name, col_names))
    
89 90
  }
  
91
  return (valid)
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 117
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)
118
    
119 120 121 122 123 124 125 126 127 128
    
    if(!is.na(aux))
      res <- TRUE
  }
  
  
  return(res)
  
}

129
check_values_not_categoric <- function(values, colname , codebook_param){
130 131 132
  
  valid_vals <- values
  
133
  possible_vals <- possible_values(colname, codebook_param)
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  
  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
    }
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 197
    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)
}

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

212
possible_values_categoric <- function(codebook_param){
213
  
214
  possible_value <- subset(harmonised_data,harmonised_data$Harmonised.variable.name==x)[1,4]
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
  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){
  
240
  data_summary <- ds.summary(x)
241
  
242
  low_quantile <- data_summary$HM$`quantiles & mean`[[1]]
243
  
244
  high_quantile <- data_summary$HM$`quantiles & mean`[[7]]
245 246 247 248 249 250
  
  return(list(low_quantile,high_quantile))
  
  
}

251
notify_error <- function(invalid_name_list,invalid_value_list,wrong_categoric, wrong_categoric_values, missing_numeric, codebook_param){
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 283
  
  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)){
284
      res <- paste(res, error_message_categoric(wrong_categoric[i], wrong_categoric_values[[i]], codebook_param), sep=" ")
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    }
  }
  
  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)
  
}

306
error_message_categoric <- function(colname, invalid_values, codebook_param){
307 308 309 310 311
  
  res<- "\nValues in the field"
  res<- paste(res, colname, sep=" ")
  res<- paste(res, "should be", sep=" ")
  
312
  range <- possible_values_categoric(colname , codebook_param)
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 342
  
  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
  
343
  range <- subset(harmonised_data, harmonised_data$Harmonised.variable.name == new_colname)
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 395
  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)
  
}

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

525 526 527 528 529 530 531
auxConnections <- connect()
connections <- auxConnections[[1]]
inp <- auxConnections[[2]]

#Conexión a la base de datos

ds.dim("data", datasources = connections)
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
colnames <- ds.colnames("data")
colnames

ds.dataFrameSubset(df.name = "data",
                   V1.name = "data$LBXAPTTA",
                   V2.name = "130",
                   Boolean.operator = "<=",
                   newobj = "inRangeHigh",
                   keep.NAs = TRUE,
                   datasources = connections)

lengthHigh <- ds.length(x='inRangeHigh$LBXAPTTA', datasources = connections)


ds.dataFrameSubset(df.name = "inRangeHigh",
                   V1.name = "inRangeHigh$LBXAPTTA",
                   V2.name = "11",
                   Boolean.operator = ">=",
                   newobj = "inRange",
                   keep.NAs = TRUE,
                   datasources = connections)

lengthBuenos <- ds.length(x='inRange$LBXAPTTA', datasources = connections)

summary <- ds.summary("inRange$LBXAPTTA")

558 559 560 561 562 563 564 565

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

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

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

567 568
check_valid_columns <- check_column_names(codebook ,data_colnames)
valid_columns <- as.data.frame(check_valid_columns$colnames)
569 570 571


result <- ""
572
result<-check_valid_values(valid_columns, codebook)
573
print(check_valid_columns)
574
datashield.logout(connections) 
575 576 577 578 579 580 581
cat(result)

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

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

582

583 584 585
cat(check_valid_columns,file=file_name,sep="\n")
cat(result,file=file_name,append=TRUE)

586
datashield.logout(connections) 
587

588