2017-02-24 72 views
0

我想在不同的文本(somename)中循環的每個結果。R For循環不必要的覆蓋

現在循環覆蓋;

library(rvest) 

main.page <- read_html(x = "http://www.imdb.com/event/ev0000681/2016") 
urls <- main.page %>% # feed `main.page` to the next step 
    html_nodes(".alt:nth-child(2) strong a") %>% # get the CSS nodes 
    html_attr("href") # extract the URLs 


for (i in urls){ 
    a01 <- paste0("http://www.imdb.com",i) 
    text <- read_html(a01) %>% # load the page 
      html_nodes(".credit_summary_item~ .credit_summary_item+ .credit_summary_item .itemprop , .summary_text+ .credit_summary_item .itemprop") %>% # isloate the text 
      html_text() 
}   

我怎麼能以這樣的方式,「我」從列表中添加文本TOT中的語句代碼呢?

+0

你需要一個空列表,將該文本存儲在其各自的索引 – eLRuLL

+0

中,但後來我只能得到文本中最後一個輸入列表的結果 – nemja

+1

您是否嘗試過文本< - sapply(url,function(i){...}) '?(**編輯**:應該使用'lapply'來代替,保持每個元素完全包含在一個列表元素中。) – r2evans

回答

2

爲了鞏固我的評論:

main.page <- read_html(x = "http://www.imdb.com/event/ev0000681/2016") 
urls <- main.page %>% # feed `main.page` to the next step 
    html_nodes(".alt:nth-child(2) strong a") %>% # get the CSS nodes 
    html_attr("href") # extract the URLs 

texts <- sapply(head(urls, n = 3), function(i) { 
    read_html(paste0("http://www.imdb.com", i)) %>% 
    html_nodes(".credit_summary_item~ .credit_summary_item+ .credit_summary_item .itemprop , .summary_text+ .credit_summary_item .itemprop") %>% 
    html_text() 
    }, simplify = FALSE) 
str(texts) 
# List of 3 
# $ /title/tt5843990/: chr [1:4] "Lav Diaz" "Charo Santos-Concio" "John Lloyd Cruz" "Michael De Mesa" 
# $ /title/tt4551318/: chr [1:4] "Andrey Konchalovskiy" "Yuliya Vysotskaya" "Peter Kurth" "Philippe Duquesne" 
# $ /title/tt4550098/: chr [1:4] "Tom Ford" "Amy Adams" "Jake Gyllenhaal" "Michael Shannon" 

如果使用lapply(...),你會得到一個無名名單,這可能會或可能不會對你的問題。相反,使用sapply(..., simplify = FALSE),我們得到一個名爲的名稱爲的列表,其中每個名稱(在本例中)是從urls檢索到的部分url。

使用sapply而不使用simplify可能會導致意想不到的輸出。舉個例子:

set.seed(9) 
sapply(1:3, function(i) rep(i, sample(3, size=1))) 
# [1] 1 2 3 

有人可能會認爲,這將總是返回一個向量。但是,如果任何返回的單元素是不一樣的長度(例如)爲他人,那麼向量變爲列表:

set.seed(10) 
sapply(1:3, function(i) rep(i, sample(3, size=1))) 
# [[1]] 
# [1] 1 1 
# [[2]] 
# [1] 2 
# [[3]] 
# [1] 3 3 

在這種情況下,最好有確定性的返回值,強制列表:

set.seed(9) 
sapply(1:3, function(i) rep(i, sample(3, size=1)), simplify = FALSE) 
# [[1]] 
# [1] 1 
# [[2]] 
# [1] 2 
# [[3]] 
# [1] 3 

這樣,您始終知道如何引用子返回。 (這是Hadley的purrr包的原則和優點之一:每個函數總是返回一個你聲明的類型的清單(包還有其他優點)。