2017-07-26 30 views
0

我有一个数据表与同一列中的.txt链接列表。我正在寻找一种方法让R在每个链接中搜索文件是否包含折扣率折扣现金流。然后,我要R在每个链接旁边创建2列(一个用于折扣率,另一个用于折扣现金流),如果存在,那么其中将有1个,如果不存在则为0。如何在一列链接中查找r中的字符串匹配?

current table with links in column websiteURL

what i want my table to look like

这里的示例链接的小单子,我想通过筛选:

http://www.sec.gov/Archives/edgar/data/1015328/0000913849-04-000510.txt 
http://www.sec.gov/Archives/edgar/data/1460306/0001460306-09-000001.txt 
http://www.sec.gov/Archives/edgar/data/1063761/0001047469-04-028294.txt 
http://www.sec.gov/Archives/edgar/data/1230588/0001178913-09-000260.txt 
http://www.sec.gov/Archives/edgar/data/1288246/0001193125-04-155851.txt 
http://www.sec.gov/Archives/edgar/data/1436866/0001172661-09-000349.txt 
http://www.sec.gov/Archives/edgar/data/1089044/0001047469-04-026535.txt 
http://www.sec.gov/Archives/edgar/data/1274057/0001047469-04-023386.txt 
http://www.sec.gov/Archives/edgar/data/1300379/0001047469-04-026642.txt 
http://www.sec.gov/Archives/edgar/data/1402440/0001225208-09-007496.txt 
http://www.sec.gov/Archives/edgar/data/35527/0001193125-04-161618.txt 
+1

'dput()'> imgs – hrbrmstr

回答

2

也许这样的事情...

checktext <- function(file, text) { 
    filecontents <- readLines(file) 
    return(as.numeric(any(grepl(text, filecontents, ignore.case = TRUE)))) 
} 

df$DR <- sapply(df$file_name, checktext, "discount rate") 
df$DCF <- sapply(df$file_name, checktext, "discounted cash flow") 

更快的版本,感谢Gregor的评论W,将

checktext <- function(file, text) { 
    filecontents <- readLines(file) 
    sapply(text, function(x) as.numeric(any(grepl(x, filecontents, 
       ignore.case = T)))) 
} 

df[,c("DR","DCF")] <- t(sapply(df$file_name, checktext, 
          c("discount rate", "discounted cash flow"))) 

或者,如果你是从网址,而不是本地文件做这件事,在上面df$websiteURL更换df$file_name。它在你提供的短名单上为我工作。

+2

连接和读取文件会很慢,但grep会很快。使用一次读取每个文件并使用两次'grep'会更有效率。让'text'在你的'checktext'函数中成为一个向量,并且使用'sapply(text,function(x)as.numeric(any(grepl(x,filecontents,ignore.case = T))))' – Gregor

+0

@格里戈是的 - 那会更快 - 非常感谢。我已将它添加到主要答案中。 –

相关问题