【问题标题】:Count number of lines in an in-built function, extract range of lines by specifying numbers计算内置函数中的行数,通过指定数字提取行范围
【发布时间】:2017-01-10 10:16:38
【问题描述】:

假设我有一个内置函数,其代码非常冗长,所以我想计算函数中的行数,并通过为某个函数提供数字范围来仅显示部分代码。

要查看函数中有多少行,我使用了tail() 函数,它会在每行前面显示数字

  tail(XYZ_Function) 

我尝试使用 head()tail() 组合,即假设我想要函数的第 145 到 150 行,所以我做到了

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

除了结合使用head()tail() 之外,R 中是否有任何可用的函数,我可以提供对象名称和两个数字来从该对象中提取行。

非常感谢您对此的任何帮助。

【问题讨论】:

    标签: r function count tail head


    【解决方案1】:

    我不确定你是否正在寻找这个,但你可以编写自己的函数:

    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" 
    

    【讨论】:

    • 我也在考虑为此目的编写自己的函数,因为似乎没有任何可用的内置函数。我试过你的功能,效果很好。您能否在您的函数中添加一条语句以显示行数,否则我将编辑没问题。因为我现在不知道你知道的范围应该是多少,我的意思是我不应该为上限设置一个大于行数的数字。谢谢,现在可以了!!
    • @Sowmya S. Manian 对不起,不知道你在找什么!
    猜你喜欢
    • 2021-10-27
    • 2020-07-09
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多