R For循环不需要的覆盖

R For loop unwanted overwrite

我希望循环的每个结果都在不同的文本(某个名称)中。

现在循环覆盖;

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()
}        

我怎样才能将列表中的 'i' 添加到 for 语句中的文本?

巩固我的评论:

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),我们得到一个 named 列表,其中每个名称(在本例中)是从 urls.[= 检索到的部分 url 21=]

使用 sapply 而不使用 simplify 会导致意外的输出。例如:

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

有人可能认为这将总是 return 一个向量。但是,如果任何单个元素 returned 的长度(例如)与其他元素不同,则向量变为列表:

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

在这种情况下,最好在return值中有确定性,强制列表:

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

这样,您总是知道如何引用子return。 (这是 Hadley 的 purrr 包的原则和优点之一:每个函数始终 return 是一个与您声明的类型完全相同的列表。(该包还有其他优点。)