grant macdonald
grant macdonald

Reputation: 25

Using Grep function with for loop

I'm having a problem with my code. This works for other values when the ID values are all in the tag matrix, however, if there's a value in the ID that's not in the tag matrix I get the error:

Error in IDintag[i] <- grep(ID[i], tag) : replacement has length zero

Thanks in advance

tag=NULL
ID=NULL

url <- readLines("http://www.afip.gob.ar/contacto")
tag <- as.matrix(grep("</strong>",url))
ID <- grep("correo",url)

for(i in 1:length(ID))
    {IDintag[i] <- grep(ID[i],tag)
    }

Upvotes: 0

Views: 288

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

No need for a loop, you can use %in% with which()

url <- readLines("http://www.afip.gob.ar/contacto")
tag <- as.matrix(grep("</strong>",url))
ID <- grep("correo", url)

matrix(which(tag %in% ID))
#      [,1]
# [1,]    3
# [2,]    4
# [3,]    5

Upvotes: 1

Related Questions