我的目標是從疾病控制中心(CDC)支持的website獲得2016年軍團病病例1996年第1周至第46周的時間序列)的美國。的同事,試圖刮掉只含有軍團菌病病例與下面的代碼表:要求疾病控制中心使用RSocrata或XML中的數據R
#install.packages('rvest')
library(rvest)
## Code to get all URLS
getUrls <- function(y1,y2,clist){
root="https://wonder.cdc.gov/mmwr/mmwr_1995_2014.asp?mmwr_year="
root1="&mmwr_week="
root2="&mmwr_table=2"
root3="&request=Submit&mmwr_location="
urls <- NULL
for (year in y1:y2){
for (week in 1:53){
for (part in clist) {
urls <- c(urls,(paste(root,year,root1,week,root2,part,root3,sep="")))
}
}
}
return(urls)
}
TabList<-c("A","B") ## can change to get not just 2 parts of the table but as many as needed.
WEB <- as.data.frame(getUrls(1996,2014,TabList)) # Only applies from 1996-2014. After 2014, the root url changes.
head(WEB)
#Example of how to extract data from a single webpage.
url <- 'https://wonder.cdc.gov/mmwr/mmwr_1995_2014.asp? mmwr_year=1996&mmwr_week=20&mmwr_table=2A&request=Submit&mmwr_location='
webpage <- read_html(url)
sb_table <- html_nodes(webpage, 'table')
sb <- html_table(sb_table, fill = TRUE)[[2]]
#test if Legionellosis is in the table. Returns a vector showing the columns index if the text is found.
#Can use this command to filter only pages that you need and select only those columns.
test <- grep("Leg", sb)
sb <- sb[,c(1,test)]
### This code only works if you have 3 columns for headings. Need to adapt to be more general for all tables.
#Get Column names
colnames(sb) <- paste(sb[2,], sb[3,], sep="_")
colnames(sb)[1] <- "Area"
sb <- sb[-c(1:3),]
#Remove commas from numbers so that you can then convert columns to numerical values. Only important if numbers above 1000
Dat <- sapply(sb, FUN= function(x)
as.character(gsub(",", "", as.character(x), fixed = TRUE)))
Dat<-as.data.frame(Dat, stringsAsFactors = FALSE)
但是,代碼還沒有完成,我想這可能是最好使用API,因爲表的結構和佈局網頁更改。這樣我們就不必梳理表格,找出佈局何時改變以及如何相應地調整網頁抓取代碼。因此我試圖從API中獲取數據。
現在,我發現了CDC提供數據的兩個幫助文檔。一位似乎從2014年開始提供數據,使用RSocrata可以看到here,而另一條指令看起來更加通用,並且使用了http格式的XML格式請求,可以看到here。通過http的XML格式請求需要一個基於數據庫的ID我找不到。然後我偶然發現了RSocrata並決定嘗試。但提供的代碼片段以及我設置的令牌標識不起作用。
install.packages("RSocrata")
library("RSocrata")
df <- read.socrata("https://data.cdc.gov/resource/cmap-p7au?$$app_token=tdWMkm9ddsLc6QKHvBP6aCiOA")
我該如何解決這個問題?我的最終目標是按國家每週收集1996年至2016年的軍團菌病病例表。
@christmetcalf我刪除了$$ app_token參數,它仍然無法工作。我收到了同樣的錯誤錯誤在read.socrata:text/plain不支持的數據格式。我經歷了線程,沒有發現對我的場景有用的東西。我試圖運行的代碼直接來自Socrata頁面。 – Meli
啊,看起來像RSocrata代碼片段中存在一個錯誤。該URL的末尾應該有一個'.csv',就像'https:// data.cdc.gov/resource/cmap-p7au.csv' – chrismetcalf
@christmetcalf該URL最後應該有一個.json。它確實有效,但它沒有提供我正在尋找的所有數據,所以我會尋找替代方案。我想從這個網絡應用程序的所有legionellosis數據'https:// wonder.cdc.gov/mmwr/mmwrmorb.asp /' – Meli