【问题标题】:Error in <my code> : object of type 'closure' is not subsettable<我的代码> 中的错误:“闭包”类型的对象不是子集
【发布时间】:2012-07-03 17:38:00
【问题描述】:

我终于能够计算出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
}

【问题讨论】:

  • 当你错误地输入[]而不是()

标签: r r-faq


【解决方案1】:

一般来说,此错误消息意味着您尝试对函数使用索引。您可以重现此错误消息,例如

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

虽然我们经常将反应式表达式视为数据帧,但它们实际上是返回数据帧(或其他对象)的函数

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

【讨论】:

    【解决方案2】:

    在尝试对其进行子集化之前,您没有定义向量 urlurl 也是基本包中的一个函数,所以 url[i] 试图子集该函数......这没有意义。

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

    【讨论】:

      【解决方案3】:

      如果出现类似错误 警告:$ 中的错误:“闭包”类型的对象不是子集 [没有可用的堆栈跟踪]

      只需使用 :: 添加相应的包名称 例如

      而不是标签(....)

      写 闪亮的::标签(....)

      【讨论】:

        【解决方案4】:

        这可能意味着一个未定义的变量。

        【讨论】:

        • 对我来说未定义的数据集。菜鸟错误。
        【解决方案5】:

        我遇到了这个问题,试图删除事件响应中的 ui 元素:

        myReactives <- eventReactive(input$execute, {
            ... # Some other long running function here
            removeUI(selector = "#placeholder2")
        })
        

        我收到了这个错误,但不是在 removeUI 元素行,由于某种原因,它出现在下一个观察者中。从 eventReactive 中取出 removeUI 方法并将其放置在其他地方为我消除了此错误。

        【讨论】:

          【解决方案6】:

          我认为你的意思是url[i] &lt;- paste(...

          而不是url[i] = paste(...。如果是这样,请将= 替换为&lt;-

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多