R中的下标越界

subscript out of bounds in R

我想从 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
 }
}

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

Error in names[[i]] : subscript out of bounds

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

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) 那样可能有效

既然你是过滤数据,我建议你使用内置的过滤功能,比如grepl

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