【问题标题】:"Argument is of length zero" error with grepl loopgrepl 循环出现“参数长度为零”错误
【发布时间】:2023-03-11 06:20:01
【问题描述】:

我遇到了涉及 grepl 的循环问题。我正在尝试打印包含字符串“Taxable Revenue by Area”的索引,但我不断收到错误 Argument is of length 0。我尝试了不同的方法,但一直出错。当我检查 grepl 语句的长度时,它是 1,而不是零。我真的被困住了! nevlists 是数据框列表。每个数据框由数字命名,1-48,因此 nevlists 的长度为 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)}}

【问题讨论】:

  • 您可能希望包含一些可重现的数据(请参阅how to ask)- 查看一些示例数据将增加有人能够提供帮助的机会。
  • 我确实添加了我使用的代码,包括指向数据源的链接,还有什么我应该添加的吗?
  • 啊,对不起-你是对的。我正在寻找字符串或其他内容的示例列表并跳过了链接。

标签: r list loops grepl


【解决方案1】:

我不是 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)
  }
}

输出一个数字索引值,这可能更有用,具体取决于您所追求的。

【讨论】:

  • 哇,谢谢卢克!这正是我想要的!你就是男人!
猜你喜欢
  • 2021-03-08
  • 1970-01-01
  • 2014-07-27
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多