2014-07-20 68 views
6

我想在Github上放一些R代碼和相關的數據文件(RData)。從Github導入數據到R(rdata)

到目前爲止,一切正常。但是當人們克隆版本庫時,我希望他們能夠立即運行代碼。目前,這是不可能的,因爲他們必須將其工作目錄(setwd)更改爲RData文件克隆(即下載)到的目錄。

因此,我認爲這可能會更容易,如果我改變R代碼,使其鏈接到github上的RData文件。但我無法使用以下代碼片段來使用它。我想也許有一些問題文本/二進制問題。

x <- RCurl::getURL("https://github.com/thefactmachine/hex-binning-gis-data/raw/master/popDensity.RData") 
y <- load(x) 

任何幫助,將不勝感激。

感謝

回答

0

load一個文件名。

x <- getURL("https://github.com/thefactmachine/hex-binning-gis-data/raw/master/popDensity.RData") 
writeLines(x, tmp <- tempfile()) 
y <- load(tmp) 
+0

感謝發佈。我嘗試了上述解決方案,但收到以下消息。我嘗試了幾個不同的文件。錯誤:壞恢復文件幻數(文件可能已損壞) - 沒有數據加載 此外:警告消息: 文件'filef00b79947a46'有幻數'' 使用2之前的保存版本已被棄用 – markthekoala

5

這個工作對我來說:

githubURL <- "https://github.com/thefactmachine/hex-binning-gis-data/raw/master/popDensity.RData" 
load(url(githubURL)) 
head(df) 
#   X  Y  Z 
# 1 16602794 -4183983 94.92019 
# 2 16602814 -4183983 91.15794 
# 3 16602834 -4183983 87.44995 
# 4 16602854 -4183983 83.79617 
# 5 16602874 -4183983 80.19643 
# 6 16602894 -4183983 76.65052 

編輯迴應OP評論。

從文檔:

Note that the https:// URL scheme is not supported except on Windows.

所以,你可以試試這個:

download.file(githubURL,"myfile") 
load("myfile") 

這對我來說也有效,但是這會弄亂你的工作目錄。如果這不起作用,請嘗試在撥打download.file(...)的電話中設置method="curl"

+0

感謝發佈。當我嘗試上面的代碼時收到以下錯誤消息:加載時出錯(url(githubURL)):無法打開我正在使用R Studio的連接。 – markthekoala

+0

我認爲問題在於使用'https'。查看我的編輯可能的工作原理 - 很難知道,因爲所有這些工作都在我的系統上運行。如果您只是將網址更改爲「http:// ...」,會發生什麼情況?這也適用於我。 – jlhoward

0

我之前也遇到過這個問題,而且我發現最可靠的解決方案是使用來自夢幻般的[devtools] [1]軟件包的微小修改source_url。這適用於我(在Mac上)。

load_url <- function (url, ..., sha1 = NULL) { 
    # based very closely on code for devtools::source_url 
    stopifnot(is.character(url), length(url) == 1) 
    temp_file <- tempfile() 
    on.exit(unlink(temp_file)) 
    request <- httr::GET(url) 
    httr::stop_for_status(request) 
    writeBin(httr::content(request, type = "raw"), temp_file) 
    file_sha1 <- digest::digest(file = temp_file, algo = "sha1") 
    if (is.null(sha1)) { 
    message("SHA-1 hash of file is ", file_sha1) 
    } 
    else { 
    if (nchar(sha1) < 6) { 
     stop("Supplied SHA-1 hash is too short (must be at least 6 characters)") 
    } 
    file_sha1 <- substr(file_sha1, 1, nchar(sha1)) 
    if (!identical(file_sha1, sha1)) { 
     stop("SHA-1 hash of downloaded file (", file_sha1, 
      ")\n does not match expected value (", sha1, 
      ")", call. = FALSE) 
    } 
    } 
    load(temp_file, envir = .GlobalEnv) 
} 

我用一個非常類似的修改,從使用read.table github上,等拿到文本文件請注意,您需要使用GitHub的URL的「原始」版本(你在你的問題包括在內)。

[1] https://github.com/hadley/devtoolspackage