首页 文章

<my code>中的错误:'closure'类型的对象不是子集表

提问于
浏览
90

我终于能够计算出my scraping的代码了 . 它似乎工作正常,然后突然再次运行它时,我收到以下错误消息:

Error in url[i] = paste("http://en.wikipedia.org/wiki/", gsub(" ", "_",  : 
  object of type 'closure' is not subsettable

我不知道为什么我在代码中没有改变任何内容 .

请指教 .

library(XML)
library(plyr)

names <- c("George Clooney", "Kevin Costner", "George Bush", "Amar Shanghavi")

for(i in 1:length(names)) {
    url[i] = paste('http://en.wikipedia.org/wiki/', gsub(" ","_", names[i]) , sep="")

    # some parsing code
}

3 回答

  • 87

    通常,此错误消息表示您已尝试在函数上使用索引 . 例如,您可以重现此错误消息

    mean[1]
    ## Error in mean[1] : object of type 'closure' is not subsettable
    mean[[1]]
    ## Error in mean[[1]] : object of type 'closure' is not subsettable
    mean$a
    ## Error in mean$a : object of type 'closure' is not subsettable
    

    错误消息中提到的闭包(松散地)是在调用函数时存储变量的函数和环境 .


    在这种特殊情况下,正如Joshua所提到的,您正在尝试将url函数作为变量访问 . 如果定义名为 url 的变量,则错误消失 .

    作为一种良好实践,通常应该避免在base-R函数之后命名变量 . (调用变量data是此错误的常见来源 . )


    尝试子集运算符或关键字有几个相关的错误 .

    `+`[1]
    ## Error in `+`[1] : object of type 'builtin' is not subsettable
    `if`[1]
    ## Error in `if`[1] : object of type 'special' is not subsettable
    

    如果您在 shiny 中遇到此问题,最可能的原因是您尝试使用 reactive 表达式而不将其作为使用括号的函数调用 .

    library(shiny)
    reactive_df <- reactive({
        data.frame(col1 = c(1,2,3),
                   col2 = c(4,5,6))
    })
    

    虽然我们经常使用闪亮的反应式表达式,就像它们是数据帧一样,但它们实际上是 functions ,它们返回数据帧(或其他对象) .

    isolate({
        print(reactive_df())
        print(reactive_df()$col1)
    })
      col1 col2
    1    1    4
    2    2    5
    3    3    6
    [1] 1 2 3
    

    但是如果我们尝试在没有括号的情况下对其进行子集化,那么我们实际上是在尝试索引函数,并且我们得到一个错误:

    isolate(
        reactive_df$col1
    )
    Error in reactive_df$col1 : object of type 'closure' is not subsettable
    
  • -4

    在尝试对其进行子集之前,不要定义向量 url . url 也是基础包中的一个函数,因此 url[i] 正在尝试对该函数进行子集化...这没有意义 .

    您可能在之前的R会话中定义了 url ,但忘记将该代码复制到您的脚本中 .

  • 31

    我觉得你的意思是 url[i] <- paste(...

    而不是 url[i] = paste(... . 如果是,请用 <- 替换 = .

相关问题