2012-03-02 3 views
5

Ce que j'essaie de faire est de charger un fichier de données à partir du répertoire local. Si ce n'est pas le cas, téléchargez-le à partir d'un serveur Web. Actuellement j'utilise un tryCatch imbriqué et il semble fonctionner. Est-ce la bonne façon d'essayer de terminer cette tâche dans R?Charger un fichier de données dans R en utilisant 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") 
    }) 
    }) 

Répondre

12

Vous pouvez utiliser la fonction file.exists(f) pour voir si un fichier existe. D'autres erreurs peuvent survenir, bien sûr, telles que des permissions ou des problèmes de format de fichier, donc vous pouvez vouloir tout emballer dans un try-block de toute façon.

Questions connexes