2012-03-02 28 views
5

Điều tôi đang cố gắng làm là tải tệp dữ liệu từ thư mục cục bộ. Nếu nó không có thì tải xuống từ máy chủ web. Hiện tại tôi đang sử dụng tryCatch lồng nhau và nó dường như hoạt động. Đây có phải là cách chính xác để hoàn thành nhiệm vụ này trong R không?Tải một tệp dữ liệu trong R bằng cách sử dụng 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") 
    }) 
    }) 

Trả lời

12

Bạn có thể sử dụng hàm file.exists(f) để xem tệp có tồn tại hay không.

Các lỗi khác có thể xảy ra, tất nhiên, chẳng hạn như quyền hoặc vấn đề định dạng tệp, vì vậy, bạn có thể muốn bao bọc mọi thứ trong khối thử.

Các vấn đề liên quan