2014-10-06 59 views
0

以下是獲取R函數幫助的功能。見下:重新定義help_console函數以獲得給定包中函數的幫助

help_console <- 
function (topic, format = c("text", "html", "latex", "Rd"), lines = NULL, 
    before = NULL, after = NULL) 
{ 
    format = match.arg(format) 
    if (!is.character(topic)) 
     topic <- deparse(substitute(topic)) 
    helpfile = utils:::.getHelpFile(help(topic)) 
    hs <- capture.output(switch(format, text = tools:::Rd2txt(helpfile), 
     html = tools:::Rd2HTML(helpfile), latex = tools:::Rd2latex(helpfile), 
     Rd = tools:::prepare_Rd(helpfile))) 
    if (!is.null(lines)) 
     hs <- hs[lines] 
    hs <- c(before, hs, after) 
    cat(hs, sep = "\n") 
    invisible(hs) 
} 

help_console(topic="lm", format = "text", lines=1) 
Fitting Linear Models 

現在我想重新定義這個函數來從給定的包得到R函數的幫助。這裏是我的MWE

help_console2 <- 
function (topic, pkg, format = c("text", "html", "latex", "Rd"), lines = NULL, 
    before = NULL, after = NULL) 
{ 
    format = match.arg(format) 
    if (!is.character(topic)) 
     topic <- deparse(substitute(topic)) 
    if (!is.character(pkg)) 
     topic <- deparse(substitute(pkg)) 
    helpfile = utils:::.getHelpFile(help(pkg, topic)) 
    hs <- capture.output(switch(format, text = tools:::Rd2txt(helpfile), 
     html = tools:::Rd2HTML(helpfile), latex = tools:::Rd2latex(helpfile), 
     Rd = tools:::prepare_Rd(helpfile))) 
    if (!is.null(lines)) 
     hs <- hs[lines] 
    hs <- c(before, hs, after) 
    cat(hs, sep = "\n") 
    invisible(hs) 
} 

help_console2(topic="lm", pkg="stats", format = "text", lines=1) 

Error in find.package(if (is.null(package)) loadedNamespaces() else package, : 
    there is no package called ‘topic’ 

這個函數拋出錯誤。任何幫助將不勝感激。由於

+0

什麼是錯誤訊息? – rseubert 2014-10-06 19:46:35

+0

我一定錯過了什麼:'help(package:function)'有什麼問題? – 2014-10-06 19:57:31

+0

@CarlWitthoft'help(package :: function)'不工作。請參閱[這裏](http://stackoverflow.com/q/26223338/707145)。 – MYaseen208 2014-10-06 20:02:30

回答

1

你有錯誤的參數順序和需要智取非標準評價:

help_console2 <- 
    function (topic, pkg, format = c("text", "html", "latex", "Rd"), lines = NULL, 
      before = NULL, after = NULL) 
    { 
    format = match.arg(format) 
    if (!is.character(topic)) 
     topic <- deparse(substitute(topic)) 
    if (!is.character(pkg)) 
     topic <- deparse(substitute(pkg)) 
    helpfile = utils:::.getHelpFile(do.call(help, list(topic=topic, package=pkg))) 
    hs <- capture.output(switch(format, text = tools:::Rd2txt(helpfile), 
           html = tools:::Rd2HTML(helpfile), latex = tools:::Rd2latex(helpfile), 
           Rd = tools:::prepare_Rd(helpfile))) 
    if (!is.null(lines)) 
     hs <- hs[lines] 
    hs <- c(before, hs, after) 
    cat(hs, sep = "\n") 
    invisible(hs) 
    } 

help_console2(topic="lm", pkg="stats", format = "text", lines=1) 
#Fitting Linear Models 
+0

感謝@Roland的幫助。 – MYaseen208 2014-10-06 19:52:34