LOOP FOR : how not to erase first API result

Hi Everyone,

I'm trying to request SERPTACK API in order to get Google SERP (Search Engine Result Page) information from several keywords.
It works very well with one keyword, but now i'm trying to create a Loop FOR in order to request several keywords. My code is working but it seems to erase the first result for keyword1.

Have you any idea how to improve my code ?

Thanks a lot

Here it is :

kw <- c("keyword1","keyword2")
google = "google_domain=google.fr"

for (i in 1:length(kw)){
json <- fromJSON(paste("http://api.serpstack.com/search?access_key=##########&query=",kw[i],"&",google,sep = ""))
organic_resulat <- json$organic_results
final_doc <- data.frame(organic_resulat)
i <- i + 1
}

You are currently overwriting the result of the json object each time the loop runs. You can separate the output from the sequence and body (see https://r4ds.had.co.nz/iteration.html#for-loops) by doing the following:

kw <- c("keyword1","keyword2")
google = "google_domain=google.fr"

output <- vector("list", length(kw))  # 1. output

for (i in 1:length(kw)){ # 2. sequence
  json <- fromJSON(paste("http://api.serpstack.com/search?access_key=##########&query=", kw[i], "&", google, sep = "")) 
  output[i] <- json$organic_results # 3. body
  #final_doc <- data.frame(organic_resulat)
  #i <- i + 1 # This is not needed
}

# See results
output
1 Like

Thanks a lot for your reply !

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.