楼主: daishen
1143 2

[程序分享] 参议员协作网络部分的代码精简 [推广有奖]

  • 0关注
  • 10粉丝

博士生

6%

还不是VIP/贵宾

-

威望
0
论坛币
3155 个
通用积分
51.3742
学术水平
67 点
热心指数
68 点
信用等级
42 点
经验
3733 点
帖子
111
精华
0
在线时间
324 小时
注册时间
2014-9-14
最后登录
2016-3-10

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
Automated Data Collection with R 第一二章的代码烦的一笔,花了一天的时间对代码进行了优化。


library(rvest)
library(RCurl)

#Generate empty folder
dir.create("Bills_111/")

# Iterate over all 4059 pieces of legislation
for(i in 1:4059){
    # Generate the unique URL for each piece of legislation
    url <- str_c(
        "http://thomas.loc.gov/cgi-bin/bdquery/D?d111:",
        i,
        ":./list/bss/d111SN.lst:@@@P"
    )
    # Download the page
    bill.result <- getURL(url)
    # Write the page to local hard drive
    write(
        bill.result, str_c(
            "Bills_111/Bill_111_S",
            i,
            ".html"
        )
    )
    # Print progress of download
    cat(i, "\n")
}


#简化部分

myfun = function(i) {
             url = str_c("Bills_111/Bill_111_S", i, ".html")
             sponsors = url %>% html() %>% html_nodes("div a") %>% html_text() %>% .[[15]] %>% gsub("Sen","",.)
             cosponsors = url %>% html() %>% html_nodes("p a") %>% html_text() %>% .[-1] %>% gsub("Sen","",.)
             list(sponsors,cosponsors)
            }

sponsor.list = lapply(1:4059,myfun)

sponsor.list[[1]][1] = " Reid, Harry"

all.senators = sponsor.list %>% unlist %>% unique %>% sort %>% .[-length(.)] #109个参议员

# Create a matrix of sponsors

sponsor.matrix = matrix(NA, nrow = 4059, ncol = length(all.senators))
colnames(sponsor.matrix) = all.senators
rownames(sponsor.matrix) = paste("S.", seq(1, 4059), sep ="")

for(i in 1:length(sponsor.list)){
    sponsor.matrix[i, which(all.senators == sponsor.list[[i]][1])] = "Sponsor"
    sponsor.matrix[i, which(all.senators %in% unlist(sponsor.list[[i]][2]))] = "Cosponsor"
    }

> sponsor.matrix[30:35,31:34]
      Cornyn, John  Crapo, Mike  DeMint, Jim  Dodd, Christopher J.
S.30 NA            NA           NA           NA                  
S.31 NA            NA           NA           NA                  
S.32 NA            NA           NA           NA                  
S.33 NA            NA           NA           NA                  
S.34 "Cosponsor"   "Cosponsor"  "Sponsor"    NA                  
S.35 "Cosponsor"   NA           NA           NA  



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:参议员 协作网 Legislation christopher Collection 参议员 网络

已有 1 人评分经验 论坛币 收起 理由
李会超 + 60 + 20 鼓励积极发帖讨论

总评分: 经验 + 60  论坛币 + 20   查看全部评分

沙发
xucaifeng66 发表于 2014-12-31 09:23:34 |只看作者 |坛友微信交流群
这个应该怎么运行?
我是说怎么把这些代码放在哪?通过什么途径实现数据的自动收集

使用道具

藤椅
ryoeng 在职认证  发表于 2015-2-9 05:41:10 |只看作者 |坛友微信交流群
提示: 作者被禁止或删除 内容自动屏蔽

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-27 19:24