View source: R/findLoops.R View source: R/findLoops.R
findLoops | R Documentation |
This finds the explicit loops in R code, for
, while
and repeat
loops.
findLoops(f, nested = TRUE, code = parse(f),
w = mkLoopWalker(nested, skipIfFalse = skipIfFalse),
skipIfFalse = TRUE)
numNestedLoops(code, recursive = TRUE)
f |
either an R language object or the path to a file containing R code which will be parsed |
nested |
a logical value that controls whether we look for loops inside loops or ignore the code in the body of a loop. |
skipIfFalse |
a logical value. If |
code |
the R code, providing a way to pass code already parsed and not necessarily in a file.
For |
w |
the code walker that collects the loop nodes. |
recursive |
a logical value, currently ignored |
This uses codetools::walkCode to traverse the abstract syntax tree
and captures nodes corresponding to these types of loops.
One could add criteria to find specific types of loops, e.g.,
with a loop variable named i
, a symbol/name as the third element of the loop (i.e., what is
being looped over) or a call to seq, seq_len, etc.,
or a while
condition that is TRUE
.
One can also post-process the results.
A list of the language objects corresponding to the loop objects found in the R code.
Duncan Temple Lang
walkCode
indexWalkCode
fns = getFunctionDefs(getNamespace("tools"))
loops = lapply(fns, function(x) findLoops(code = x))
nl = sapply(loops, length)
table(nl)
# These include nested loops.
which.max(nl)
# Let's look at all the loops and the number of calls in each
loops2 = unlist(loops, recursive = FALSE)
length(loops2)
summary(sapply(loops2, numCalls))
# number of nested loops.
nn = sapply(loops2, numNestedLoops)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.