2014-01-06 42 views
2

我有一個我想用lapply的數據框。我選擇了第一列在這裏的第一個值:關於tm語料庫函數的lapply行爲

link <- c(
    "http://www.r-statistics.com/tag/hadley-wickham/",              
    "http://had.co.nz/",                      
    "http://vita.had.co.nz/articles.html",                 
    "http://blog.revolutionanalytics.com/2010/09/the-r-files-hadley-wickham.html",       
    "http://www.analyticstory.com/hadley-wickham/" 
)    

以獲取鏈接,並將其存儲的內容轉換成文集[感謝適用於agstudy]

create.corpus <- function(url.name){ 
    doc=htmlParse(link) 
    parag=xpathSApply(doc,'//p',xmlValue) 
    cc=Corpus(VectorSource(parag)) 
    meta(cc,type='corpus','link')=link 
    return(cc) 
} 

的功能,但我不能讓通過lapply工作的功能:

cc=lapply(link,create.corpus) # does not work 
cc=lapply(link,nchar) # works 

link=link[1] # try on single element 
cc=create.corpus(link) # works 

爲什麼這個函數在lapply中不起作用?

回答

2

您的功能存在問題。將link的所有實例替換爲url.name,它將起作用。

# library(XML); library(tm) 

create.corpus <- function(url.name){ 
    doc=htmlParse(url.name) 
    parag=xpathSApply(doc,'//p',xmlValue) 
    cc=Corpus(VectorSource(parag)) 
    meta(cc,type='corpus','link') <- url.name 
    return(cc) 
} 

cc <- lapply(link, create.corpus) 

結果:

> cc 
[[1]] 
A corpus with 48 text documents 

[[2]] 
A corpus with 2 text documents 

[[3]] 
A corpus with 41 text documents 

[[4]] 
A corpus with 25 text documents 

[[5]] 
A corpus with 39 text documents 
+0

的感謝!有用。 – Henk

相關問題