【问题标题】:How to convert for loop into function in r?如何将for循环转换为r中的函数?
【发布时间】:2020-01-14 23:57:25
【问题描述】:

我想创建一个函数来 scape 包含 for 循环的 Web URL 数据列表:

news_url <- c()
news_date <-c() 
for (date_i in DATE){
for (page_i in PAGE){
  dt <- format(as.Date(date_i,origin="1970-01-01"), "%Y.%m.%d")
  naver_url <- paste0(naver_url_1,QUERY,naver_url_2,dt,naver_url_3,dt,naver_url_4,page_i)
  html <- read_html(naver_url)
  temp <- unique(html_nodes(html,'#main_pack')%>% 
                   html_nodes(css='.news ')%>%     
                   html_nodes(css='.type01')%>%
                   html_nodes('a')%>%
                   html_attr('href'))
  news_url <- c(news_url,temp)
  news_date <- c(news_date,rep(dt,length(temp)))
}
}

你能告诉我如何编码吗?

【问题讨论】:

  • 以上代码是您已经拥有的并且您要求对当前代码进行一些小的调整吗?

标签: r function for-loop


【解决方案1】:

您可能需要根据您从dttemp 获得的数据以及您希望最终输出的样子对output 进行一些更改。但是,这样的事情应该会有所帮助。

library(rvest)

scrape_page <- function(x, y) {

 dt <- format(as.Date(x,origin="1970-01-01"), "%Y.%m.%d")
 naver_url <- paste0(naver_url_1,QUERY,naver_url_2,dt,naver_url_3,dt,naver_url_4,y)
 html <- read_html(naver_url)
 temp <- unique(html_nodes(html,'#main_pack')%>% 
               html_nodes(css='.news ')%>%     
               html_nodes(css='.type01')%>%
               html_nodes('a')%>%
               html_attr('href'))
  return(list(news_date = dt, news_url = temp))
}

然后使用

output <- lapply(DATE, function(x) lapply(PAGE, function(y) scrape_page(x, y)))

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2020-06-03
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    相关资源
    最近更新 更多