r - <我的</code> : object of type 'closure' is not subsettable 中的错误

标签 r r-faq

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

最佳答案

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

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

虽然我们经常使用 Shiny 的响应式(Reactive)表达式,就好像它们是数据框一样,它们实际上是 功能 返回数据帧(或其他对象)。
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

关于r - <我的</code> : object of type 'closure' is not subsettable 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989246/

相关文章:

r - 将数据框字符串列拆分为多列

R 将非常大的数据表列表合并到一个 data.table 中

r - R 中的 na.strings = c()

r - full_join 0 行数据

performance - 加速R中的循环操作

r - 如何检查 R 中的操作系统

r - 为什么这一单向方差分析没有 F 统计量和 p 值?

r - 如何加快 data.table 中的逐行操作

r - 如何一次导入多个.csv文件?

r - 从数据框中提取特定列