grepl循环出现“参数长度为零”错误

时间:2018-08-20 18:49:11

标签: r list loops grepl

我遇到涉及grepl的循环问题。我正在尝试打印包含字符串“按地区划分的应税收入”的索引,但是我不断收到错误“参数长度为零”。我已经尝试了不同的方法,但是一直出错。当我检查grepl语句的长度时,它是1,而不是零。我真的被卡住了! nevlists是数据帧的列表。每个数据框均用数字1-48命名,因此nevlist的长度为48。当我在页面上自己运行grepl语句时,我需要:grepl(“ Taxable Revenue by Area”,nevlists $ '48'[ 3,]的计算结果为TRUE,这正是我要寻找的。出于某种原因,我只是无法将其适应于循环。

library(readr)
library(stringr)
library(magrittr)
library(dplyr)
library(tidyr)
library(pdftools)

 nvsr65_05 <- pdf_text("https://gaming.nv.gov/modules/showdocument.aspx?documentid=13542")

 getstats<- function(nvsr65_05){

listofdfs <- list() #Create a list in which you intend to save your df's.

for (i in 1:length(nvsr65_05)) {
table_data2 <- nvsr65_05[[i]] %>%
str_split(pattern = "\n")
table_data2 <- data.frame(matrix(unlist(table_data2)))
listofdfs[[i]] <- table_data2
}

return(listofdfs)
}


nevlists <- getstats(nvsr65_05)
names(nevlists) <-c(1:48)

for (i in 1:length(nevlists)) {
  if(grepl("Taxable Revenue by Area", nevlists$'i'[3,]) == TRUE){
    print(i)}}

#Try2

for (i in 1:length(nevlists)) {
if(as.numeric(grepl("Taxable Revenue by Area", nevlists$'i'[3,])) > 0){
print(i)}}

1 个答案:

答案 0 :(得分:0)

我不确定100%,但是我认为这是由于您建立索引的方式-尝试:

for (i in names(nevlists)) {
  # Get the index as a character instead of numeric
  # in case your names are something other than pure numbers as 
  # in this example
  ix = paste(i)
  if (grepl("Taxable Revenue by Area", nevlists[[ix]][3, ]) == TRUE) {
    print(ix)
  }
}

这只会为我打印“ 48”,这就是您所期望的吗?

如果您实际上并不关心列表项的名称,则可以完全忽略对列表项的命名,只需执行以下操作:

for (i in 1:length(nevlists)) {
  if (grepl("Taxable Revenue by Area", nevlists[[i]][3, ]) == TRUE) {
    print(i)
  }
}

输出数字索引值,根据您的需求,该值可能会更有用。