我的目标是从美国疾病控制中心(CDC)支持的websit e获得2016年第1周至第46周的军团病病例的时间序列。一位同事试图只用下面的代码刮掉含有军团病病例的桌子:
#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,而另一个指令看起来更通用,并且使用XML格式请求而不是http,可以看到here。XML格式请求超过http需要一个我找不到的数据库ID。然后我偶然发现了RSocrata并决定试试。但是我提供的代码片段以及我设置的令牌ID都不起作用。
install.packages("RSocrata")
library("RSocrata")
df <- read.socrata("https://data.cdc.gov/resource/cmap-p7au?$$app_token=tdWMkm9ddsLc6QKHvBP6aCiOA")
我该如何解决这个问题?我的最终目标是每年由州政府提供1996年至2016年的军团病病例表。
答案 0 :(得分:0)
我建议查看this issue thread in the RSocrata GitHub repo,他们正在讨论将令牌传递到RSocrata库的类似问题。
与此同时,您实际上可以不使用$$app_token
参数,只要您没有充斥我们的请求,它就会正常工作。如果没有使用应用令牌,您可以潜入限制。