Reputation: 6874
I have a recursive function that extracts data from a database. The database is huge and the recursion takes a while and eventually ends in an Error as I have exceeded the stack. I am trying to debug the function so I would like to limit the recursion so I can look at the result before the stack error occurs.
Here is the function. How can I put a recursion limit on it?
(df$relatedIdEx
is just a character string from the dataframe that is used as the string to lookup a new dataframe with). If the string has already been looked up then it is skip- this is to prevent infinite loops
get_all_dfs <- function(df) {
lapply(df$relatedIdEx, function(elem) {
if (as.character(unlist(elem)) %in% already_lookedup) {
print(paste("Already looked up ",elem," and skipping!"))
return (NULL)
} else {
already_lookedup <<- c(already_lookedup,as.character(unlist(elem)))
}
next_df <- myGIConcepts(elem)
#next_df_list<-list(next_df,my_env)
if (nrow(next_df)>1) {
get_all_dfs(next_df)
} else {
thelist<-df
}
})
}
Upvotes: 0
Views: 65
Reputation: 2425
You can pass the counter to the function, which is a bit more clean, such as get_all_dfs <- function(df,counter)
. But your question implies a quick solution will do. A counter is added as follows. Note you could move it within the lapply as well, potentially, depending on where you want the counter to be or where to break.
counter <- 0
get_all_dfs <- function(df) {
counter <<- counter+1
if (counter > 100) return (NULL)
lapply(df$relatedIdEx, function(elem) {
if (as.character(unlist(elem)) %in% already_lookedup) {
print(paste("Already looked up ",elem," and skipping!"))
return (NULL)
} else {
already_lookedup <<- c(already_lookedup,as.character(unlist(elem)))
}
next_df <- myGIConcepts(elem)
#next_df_list<-list(next_df,my_env)
if (nrow(next_df)>1) {
get_all_dfs(next_df)
} else {
thelist<-df
}
})
}
Upvotes: 1