2012-03-02 10 views
5

私がしようとしているのは、ローカルディレクトリからデータファイルをロードすることです。それがない場合は、Webサーバーからダウンロードしてください。現在、ネストされたtryCatchを使用していますが、動作するようです。これは、Rでこのタスクを完了しようとする正しい方法ですか?tryCatchを使ってRでデータファイルをロード

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") 
    }) 
    }) 

答えて

12

ファンクションfile.exists(f)を使用してファイルが存在するかどうかを確認できます。

他のエラーが発生する可能性があります(もちろん、アクセス許可やファイル形式の問題など)。したがって、とにかくtryブロック内のすべてを折り返したい場合があります。