123

我终于能够为我的抓取工作制定代码。它似乎工作正常,然后突然当我再次运行它时,我收到以下错误消息:

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

6 回答 6

137

通常,此错误消息意味着您已尝试对函数使用索引。您可以重现此错误消息,例如

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
于 2012-07-03T10:16:00.230 回答
38

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

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

于 2012-07-03T10:01:21.007 回答
1

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

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

而不是标签(....)

写闪亮的::tags(....)

于 2019-10-03T12:01:37.727 回答
1

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

于 2021-03-02T10:48:33.420 回答
0

我有这个问题是试图删除事件反应中的 ui 元素:

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

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

于 2019-06-17T09:23:04.243 回答
-5

我想你打算这样做url[i] <- paste(...

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

于 2016-12-19T17:27:24.487 回答