Search code examples
rfunctioncounttailhead

Count number of lines in an in-built function, extract range of lines by specifying numbers


Lets say I have an in built function whose code is very lengthy, so I want to count the number of lines in the function and display just part of code by providing the range of numbers to some function.

To see how many lines are there in a function, I used tail() function, which will display numbers in front of each line

  tail(XYZ_Function) 

I tried using head() and tail() combination, i.e. lets say I want from lines 145 to 150 of a function, so I did

  tail(head(XYZ_Function,n=150),n=5) 

Is there any function available in R besides using head() and tail() in combination where I can just provide object name, and two numbers to extract the lines from that object.

Any help on this is highly appreciated.


Solution

  • I am not sure if you are looking for this one, but you could write youre own function:

    code_block <- function(x, y, z) { # x = your function, y = lower limit, z = upper limit
      dat <- data.frame(head(x, n = z))
      dat[which(as.numeric(rownames(dat)) >= y  & as.numeric(rownames(dat)) <= z), ]
    }
    
    
    code_block(summary.lm, 12, 20)
    
    
    
    > code_block(summary.lm, 10, 20)
    
    10         w <- z$weights                                                  
    11         if (is.null(w)) {                                               
    12             rss <- sum(r^2)                                             
    13         }                                                               
    14         else {                                                          
    15             rss <- sum(w * r^2)                                         
    16             r <- sqrt(w) * r                                            
    17         }                                                               
    18         resvar <- rss/rdf                                               
    19         ans <- z[c("call", "terms", if (!is.null(z$weights)) "weights")]
    20         class(ans) <- "summary.lm"