2012-03-02 17 views
5

Lo que estoy tratando de hacer es cargar un archivo de datos desde el directorio local. Si no está allí, descárguelo de un servidor web. Actualmente estoy usando un TryCatch anidado y parece funcionar. ¿Es esta la manera correcta de intentar completar esta tarea en R?cargar un archivo de datos en R utilizando TryCatch

tryCatch( 
    { 
    #attempt to read file from current directory 
    # use assign so you can access the variable outside of the function 
    assign("installations", read.csv('data.csv'), envir=.GlobalEnv) 
    print("Loaded installation data from local storage") 
    }, 
    warning = function(w) 
    { 
    print()# dummy warning function to suppress the output of warnings 
    }, 
    error = function(err) 
    { 
    print("Could not read data from current directory, attempting download...") 
    #attempt to read from website 
    tryCatch(
    { 
     # use assign so you can access the variable outside of the function 
     assign("installations", read.csv('http://somewhere/data.csv'), envir=.GlobalEnv) 
     print("Loaded installation data from website") 
    }, 
    warning = function(w) 
    { 
     print()# dummy warning function to suppress the output of warnings 
    }, 
    error = function(err) 
    { 
     print("Could not load training data from website!! Exiting Program") 
    }) 
    }) 

Respuesta

12

Puede usar la función file.exists(f) para ver si existe un archivo. pueden ocurrir

Otros errores, por supuesto, como permisos o problemas de formato de archivo, así que sería bueno para envolver todo en un intento de bloque de todos modos.

Cuestiones relacionadas