Reputation: 284
I am trying to write a for loop that provides the author's short ID to a database called RePEc and gets the affiliation data. So far, this is what I have (NB: USERCODE only works on my IP):
url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="
for(i in 1:length(df_affiliations)){
Sys.sleep(1)
affiliation_fun <- paste(url,df_affiliations$author_reg_1[i])
affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation") %>% unlist(use.names=FALSE)
affiliation_1 <- paste(unlist(affiliation_run), collapse =" ")
df_affiliations$vector <- rbind(affiliation_1)
}
Every time I try this, I either get only the last value or a HTTP Error 400. For loops are not my strong suit. Can anyone figure out where I've gone wrong? Thanks in advance for your help!
Upvotes: 1
Views: 93
Reputation: 24089
Your loop is over writing your output variable on each iteration. A solution here is to initialize an empty vector outside of the loop and then assign the value to each index:
url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="
#define empty vector
affiliation_1<-vector(length=length(df_affiliations))
for(i in 1:length(df_affiliations)){
Sys.sleep(1)
affiliation_fun <- paste0(url,df_affiliations$author_reg_1[i])
affiliation_run <- fromJSON(affiliation_fun) %>% select(affiliation) %>% unlist(use.names=FALSE)
affiliation_1[i] <- paste(unlist(affiliation_run), collapse =" ")
}
This is untested since the question is not reproducible, but should provide a starting point for your final solution.
Upvotes: 2