Map function definition in R

31 Views Asked by At

if I have the following code saved in function.R

#' This function is cool
#' 
#' blablabla.....
#' @export
#' @param hello a parameter of my function
f_cool <- function(hello) {
  # some code
  # some other code
}

Is there a way to extract the outline by line number in a list or alike For example

map_fn_definition("function.R")
#> $f_cool
#> $f_cool$line_start 
#> 6
#> $f_cool$line_end 
#> 9
#> f_cool$title
#> "This function is cool"

there is possibly something possible with roxygen2. But the documentation focuses on the real goal of roxygen (generate .Rd files in packages)

Thanks!

1

There are 1 best solutions below

0
G. Grothendieck On

Try getParseData in the utils package. (Also look at xml_parse_data in the xmlparsedata package.)

getParseData(parse("function.R"))

giving

   line1 col1 line2 col2 id parent          token terminal                                       text
1      1    1     1   24  1    -35        COMMENT     TRUE                   #' This function is cool
4      2    1     2    3  4    -35        COMMENT     TRUE                                        #' 
7      3    1     3   17  7    -35        COMMENT     TRUE                          #' blablabla.....
10     4    1     4   10 10    -35        COMMENT     TRUE                                 #' @export
13     5    1     5   42 13    -35        COMMENT     TRUE #' @param hello a parameter of my function
35     6    1     9    1 35      0           expr    FALSE                                           
16     6    1     6    6 16     18         SYMBOL     TRUE                                     f_cool
18     6    1     6    6 18     35           expr    FALSE                                           
17     6    8     6    9 17     35    LEFT_ASSIGN     TRUE                                         <-
34     6   11     9    1 34     35           expr    FALSE                                           
19     6   11     6   18 19     34       FUNCTION     TRUE                                   function
20     6   19     6   19 20     34            '('     TRUE                                          (
21     6   20     6   24 21     34 SYMBOL_FORMALS     TRUE                                      hello
22     6   25     6   25 22     34            ')'     TRUE                                          )
31     6   27     9    1 31     34           expr    FALSE                                           
24     6   27     6   27 24     31            '{'     TRUE                                          {
26     7    3     7   13 26     31        COMMENT     TRUE                                # some code
28     8    3     8   19 28     31        COMMENT     TRUE                          # some other code
30     9    1     9    1 30     31            '}'     TRUE                                          }