Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose command order in a function based on an error [R]

I have three files in a folder with the following names:

./multiqc_data$ ls 
file1.json
file2.json
file3.json

When I open the files with the TidyMultiqc package existing NA values in the files might lead to the following error:

files <- dir(path,pattern = "*.json")        #locate files
files %>% 
  map(~ load_multiqc(file.path(path, .)))    #parse them

## the error
Error in parse_con(txt, bigint_as_char) : 
  lexical error: invalid char in json text.
                  "mapped_failed_pct": NaN,                 "paired in
                     (right here) ------^

I want to create a function to handle this error.

I want every time this error pops up to be able to apply this sed function in all files of the folder.

system(paste("gsed -i 's/NaN/null/g'",paste0(path,"*.json")))

Any ideas how can I achieve this

like image 396
LDT Avatar asked Apr 29 '26 11:04

LDT


1 Answers

You could use this wrapper :

safe_load_multiqc <- function(path, file) {
  tryCatch(load_multiqc(file.path(path, file)), error = function(e) {
    system(paste("gsed -i 's/NaN/null/g'",paste0(path,"*.json")))
    # retry
    load_multiqc(path, file)
  })
}
like image 158
Moody_Mudskipper Avatar answered May 02 '26 08:05

Moody_Mudskipper