2017-02-24 71 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包的原则和优点之一:每个函数总是返回一个你声明的类型的清单(包还有其他优点)。