【问题标题】:Why is my R for loop not running all the actions in the brackets?为什么我的 R for 循环没有运行括号中的所有操作?
【发布时间】:2020-12-02 13:31:27
【问题描述】:
data_before <- read_excel("C:/Users/babyb/Desktop/Derrick Rancourt/Canadian Biotech Companies.xlsx", col_names = FALSE)
companyName <- subset(na.omit(data_before, cols = 1), select = -c(2, 3, 4))
data_now <- setNames(data.table(matrix(nrow=0, ncol=2)), c("Company Name", "Website"))

for(value in companyName){
        searchTerm <- paste(value)
        print(searchTerm)
        firstLink <- get_link(searchTerm)
        print(firstLink)
        #this_row <- data.frame(value, firstLink)
        #names(this_row)<-c("Company Name", "Website")
        #data_now <- rbind(data_now, this_row)
}

get_link 是先前定义的函数。 如果 companyName 是

    1  
1   a 
2   3
3   b
4   2

然后打印搜索词打印

[1] a
[2] 3
[3] b
[4] 2

正如预期的那样。但 打印第一个链接只打印

[1] get_link("a")

,当我想要它打印时

[1] get_link("a")
[2] get_link("3")
[3] get_link("b")
[4] get_link("2")

我正在使用来自以下答案 https://stackoverflow.com/a/57441619/14084227 的 get_first_google 链接代码 代码是:

get_first_google_link <- function(name, root = TRUE) {
  url = URLencode(paste0("https://www.google.com/search?q=",name))
  page <- xml2::read_html(url)
  # extract all links
  nodes <- rvest::html_nodes(page, "a")
  links <- rvest::html_attr(nodes,"href")
  # extract first link of the search results
  link <- links[startsWith(links, "/url?q=")][1]
  # clean it
  link <- sub("^/url\\?q\\=(.*?)\\&sa.*$","\\1", link)
  # get root if relevant
  if(root) link <- sub("^(https?://.*?/).*$", "\\1", link)
  link
}

为什么它没有按预期运行? 上面概述了期望。我正在使用 r。我已经展示了来自 rstudio 的控制台。有人可以帮忙吗?

【问题讨论】:

  • 获取 get_link 函数的内容会有所帮助。
  • get_link 是我上面添加的 get_first_google_link 代码

标签: r dataframe for-loop data.table


【解决方案1】:

循环不起作用,因为 companyName 在您的循环中属于“data.frame”类,因此只有第一行被使用:

for(value in companyName)

您只需使用unlist 将其转换为向量,如下所示:

companyName <- unlist(subset(na.omit(data_before, cols = 1), select = -c(2, 3, 4)))

并且循环应该可以工作。

【讨论】:

    猜你喜欢
    • 2014-12-05
    • 2014-05-07
    • 2023-01-27
    • 2021-10-16
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    相关资源
    最近更新 更多