【问题标题】:subscript out of bounds in RR中的下标越界
【发布时间】:2018-03-02 21:27:07
【问题描述】:

我想从names 中删除某些元素。

names 是一个字符列表。在我运行以下循环后:

for (i in 1:length(names)){
  if((str_detect(names[[i]], "  Organisation Name")) || 
  (str_detect(names[[i]], "^ $")) || (str_detect(names[[i]], "^0$")) || 
  (str_detect(names[[i]], "^$"))  ){
   names[[i]] <- NULL
 }
}

我得到一个错误。错误是:

名称错误[[i]]:下标越界

【问题讨论】:

  • 寻求帮助时,您应该包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出。
  • 我猜当你杀死名字的元素时,“i”向量仍然会迭代到原始长度,所以你最终会抓住一个越界元素。也许尝试从长度(名称):1向后迭代?即使我猜对了,@MrFlick 关于可重复的示例也是正确的,您应该为后代编辑问题!

标签: r regex text-mining stringr


【解决方案1】:

这里有一些代码说明了我根据我的评论认为正在发生的事情。

names <- lapply(1:5, list)
for (i in 1:length(names)) {
  names[[i]] <- NULL
  print(sprintf('Length is now %d, i is now %i', length(names), i))
  print(names[[i]])
}

这个输出

[1] "Length is now 4, i is now 1"
[[1]]
[1] 2

[1] "Length is now 3, i is now 2"
[[1]]
[1] 4

[1] "Length is now 2, i is now 3"
Error in names[[i]] : subscript out of bounds

如果你向后迭代,就像 for (i in length(names):1) 那样可能会起作用

【讨论】:

    【解决方案2】:

    由于您是过滤数据,我建议您使用内置的过滤功能,例如grepl

    将所有正则表达式合并为一个,以获得更好的性能和紧凑性。

    【讨论】:

    • 谢谢,@Anony-Mousse。没错。
    猜你喜欢
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多