2017-08-01 22 views
9

Mam problem z dokumentacją klasy R6 i jej metod. Moim celem jest uzyskanie autouzupełniania w RStudio dla metod. W tej chwili otrzymuję tylko nazwę metody, ale nie otrzymuję informacji pomocniczych, które normalnie uzyskuję przy użyciu roxygen2 dokumentowania funkcji z parametrami itp.Dokumentowanie klas i metod R6 w pakiecie R w RStudio

Czy ktoś może mi w tym pomóc?

W tej chwili, to moja klasa:

#' @importFrom R6 R6Class 
MQParameters <- R6::R6Class(
    'MQParameters', 
    public=list(
    initialize=function(file_path=NA) { 
     private$location <- file_path 
     mq_parameters <- read.delim(file_path, stringsAsFactors=FALSE) 
     mq_parameters <- 
     setNames(mq_parameters$Value, mq_parameters$Parameter) 
     private$mq_version <- unname(mq_parameters['Version']) 
     private$fasta_file <- 
     gsub('\\\\', '/', strsplit(mq_parameters['Fasta file'], ';')[[1]]) 
    }, 
    # this method returns the version 
    getVersion=function() { 
     private$mq_version 
    }, 
    # this methods returns the fastafile. 
    # @param new_param it is possible to rewrite the basedir. 
    getFastaFile=function(new_basedir=NA) { 
     if(is.na(new_basedir)) { 
     private$fasta_file 
     } else { 
     file.path(new_basedir, basename(private$fasta_file)) 
     } 
    } 
), 
    private=list(
    location=NULL, 
    mq_version=NULL, 
    fasta_file=NULL 
) 
) 

Jeśli jesteś zainteresowany, aby przetestować tę klasę, tu jest trochę powtarzalne przykład:

df <- data.frame(Parameter=c('Version', 'Fasta file'), 
       Value=c('1.5.2.8','c:\\a\\b.fasta')) 
write.table(df, 'jnk.txt', sep='\t', row.names=F) 

p <- MQParameters$new('jnk.txt') 
p$getVersion() 
# [1] "1.5.2.8" 
p$getFastaFile() 
# [1] "c:/a/b.fasta" 
p$getFastaFile(new_basedir='.') 
# [1] "./b.fasta" 

nie wiem jak parametry dokumentu, ponieważ parametry faktycznie należą do twórcy, ale nie do klasy. A co z parametrami do innych metod w ramach funkcji?
Jaki jest preferowany sposób udokumentowania klasy za pomocą jej metod?

Chciałbym uzyskać "normalną" funkcjonalność z RStudio, jak uderzenie F1, aby przejść bezpośrednio do strony pomocy.

Każda rada jest bardzo pożądana.

Poszukując w Internecie, widziałem już kilka raportów na temat githuba na ten temat, ale mają one więcej niż 1 rok i mam nadzieję, że są tam dobre wieści lub przynajmniej dobra praktyka.

UPDATE:

Dzięki odpowiedzią mikeck Mam teraz piękny dokumentacji dla klasy i to metodami. Ale co ja wciąż brakuje, jest możliwość, aby uzyskać podpowiedź funkcji/metody i jej argumentów jak w tym zrzucie dla wspólnej funkcji:

rStudio help on functions

Zastanawiam się, czy mogę jakoś zarejestrować funkcję ręcznie, ale ponieważ nie ma określonej nazwy (zawsze jest sprzężona ze zmienną objectname, której używasz dla obiektu OBJECTNAME$methodeCall()) nie wiem jak to zrobić.

Odpowiedz

5

Rozumiem, że najłatwiej jest udokumentować obiekt NULL z tą samą klasą, co @name, ponieważ zapewnia to maksymalną elastyczność. Używam klasy R6 w jednym z moich pakietów; możesz zobaczyć roxygen here. Poniżej zamieściłem małą próbkę:

#' Python Environment 
#' 
#' The Python Environment Class. Provides an interface to a Python process. 
#' 
#' 
#' @section Usage: 
#' \preformatted{py = PythonEnv$new(port, path) 
#' 
#' py$start() 
#' 
#' py$running 
#' 
#' py$exec(..., file = NULL) 
#' py$stop(force = FALSE) 
#' 
#' } 
#' 
#' @section Arguments: 
#' \code{port} The port to use for communication with Python. 
#' 
#' \code{path} The path to the Python executable. 
#' 
#' \code{...} Commands to run or named variables to set in the Python process. 
#' 
#' \code{file} File containing Python code to execute. 
#' 
#' \code{force} If \code{TRUE}, force the Python process to terminate 
#' using a sytem call. 
#' 
#' @section Methods: 
#' \code{$new()} Initialize a Python interface. The Python process is not 
#' started automatically. 
#' 
#' \code{$start()} Start the Python process. The Python process runs 
#' asynchronously. 
#' 
#' \code{$running} Check if the Python process is running. 
#' 
#' \code{$exec()} Execute the specified Python 
#' commands and invisibly return printed Python output (if any). 
#' Alternatively, the \code{file} argument can be used to specify 
#' a file containing Python code. Note that there will be no return 
#' value unless an explicit Python \code{print} statement is executed. 
#' 
#' \code{$stop()} Stop the Python process by sending a request to the 
#' Python process. If \code{force = TRUE}, the process will be 
#' terminated using a system call instead. 
#' 
#' @name PythonEnv 
#' @examples 
#' pypath = Sys.which('python') 
#' if(nchar(pypath) > 0) { 
#' py = PythonEnv$new(path = pypath, port = 6011) 
#' py$start() 
#' py$running 
#' py$stop(force = TRUE) 
#' } else 
#' message("No Python distribution found!") 
NULL 

#' @export 
PythonEnv = R6::R6Class("PythonEnv", cloneable = FALSE, 
    # actual class definition... 

Istnieją inne alternatywne (ale podobne) implementacje; this example wykorzystuje @docType class które mogą Ci odpowiadać lepsze:

#' Class providing object with methods for communication with lightning-viz server 
#' 
#' @docType class 
#' @importFrom R6 R6Class 
#' @importFrom RCurl postForm 
#' @importFrom RJSONIO fromJSON toJSON 
#' @importFrom httr POST 
#' @export 
#' @keywords data 
#' @return Object of \code{\link{R6Class}} with methods for communication with lightning-viz server. 
#' @format \code{\link{R6Class}} object. 
#' @examples 
#' Lightning$new("http://localhost:3000/") 
#' Lightning$new("http://your-lightning.herokuapp.com/") 
#' @field serveraddress Stores address of your lightning server. 
#' @field sessionid Stores id of your current session on the server. 
#' @field url Stores url of the last visualization created by this object. 
#' @field autoopen Checks if the server is automatically opening the visualizations. 
#' @field notebook Checks if the server is in the jupyter notebook mode. 
#' #' @section Methods: 
#' \describe{ 
#' \item{Documentation}{For full documentation of each method go to https://github.com/lightning-viz/lightining-r/} 
#' \item{\code{new(serveraddress)}}{This method is used to create object of this class with \code{serveraddress} as address of the server object is connecting to.} 
#' 
#' \item{\code{sethost(serveraddress)}}{This method changes server that you are contacting with to \code{serveraddress}.} 
#' \item{\code{createsession(sessionname = "")}}{This method creates new session on the server with optionally given name in \code{sessionname}.} 
#' \item{\code{usesession(sessionid)}}{This method changes currently used session on the server to the one with id given in \code{sessionid} parameter.} 
#' \item{\code{openviz(vizid = NA)}}{This method by default opens most recently created by this object visualization. If \code{vizid} parameter is given, it opens a visualization with given id instead.} 
#' \item{\code{enableautoopening()}}{This method enables auto opening of every visualisation that you create since that moment. Disabled by default.} 
#' \item{\code{disableautoopening()}}{This method disables auto opening of every visualisation that you create since that moment. Disabled by default.} 
#' \item{\code{line(series, index = NA, color = NA, label = NA, size = NA, xaxis = NA, yaxis = NA, logScaleX = "false", logScaleY = "false")}}{This method creates a line visualization for vector/matrix with each row representing a line, given in \code{series}.} 
#' \item{\code{scatter(x, y, color = NA, label = NA, size = NA, alpha = NA, xaxis = NA, yaxis = NA)}}{This method creates a scatterplot for points with coordinates given in vectors \code{x, y}.} 
#' \item{\code{linestacked(series, color = NA, label = NA, size = NA)}}{This method creates a plot of multiple lines given in matrix \code{series}, with an ability to hide and show every one of them.} 
#' \item{\code{force(matrix, color = NA, label = NA, size = NA)}}{This method creates a force plot for matrix given in \code{matrix}.} 
#' \item{\code{graph(x, y, matrix, color = NA, label = NA, size = NA)}}{This method creates a graph of points with coordinates given in \code{x, y} vectors, with connection given in \code{matrix} connectivity matrix.} 
#' \item{\code{map(regions, weights, colormap)}}{This method creates a world (or USA) map, marking regions given as a vector of abbreviations (3-char for countries, 2-char for states) in \code{regions} with weights given in \code{weights} vector and with \code{colormap} color (string from colorbrewer).} 
#' \item{\code{graphbundled(x, y, matrix, color = NA, label = NA, size = NA)}}{This method creates a bundled graph of points with coordinates given in \code{x, y} vectors, with connection given in \code{matrix} connectivity matrix. Lines on this graph are stacked a bit more than in the \code{graph} function.} 
#' \item{\code{matrix(matrix, colormap)}}{This method creates a visualization of matrix given in \code{matrix} parameter, with its contents used as weights for the colormap given in \code{colormap} (string from colorbrewer).} 
#' \item{\code{adjacency(matrix, label = NA)}}{This method creates a visualization for adjacency matrix given in \code{matrix} parameter.} 
#' \item{\code{scatterline(x, y, t, color = NA, label = NA, size = NA)}}{This method creates a scatterplot for coordinates in vectors \code{x, y} and assignes a line plot to every point on that plot. Each line is given as a row in \code{t} matrix.} 
#' \item{\code{scatter3(x, y, z, color = NA, label = NA, size = NA, alpha = NA)}}{This method creates a 3D scatterplot for coordinates given in vectors \code{x, y, z}.} 
#' \item{\code{image(imgpath)}}{This method uploads image from file \code{imgpath} to the server and creates a visualisation of it.} 
#' \item{\code{gallery(imgpathvector)}}{This method uploads images from vector of file paths \code{imgpathvector} to the server and creates a gallery of these images.}} 


Lightning <- R6Class("Lightning", 
... 
) 

EDIT

Jeśli szukasz sposobu, aby uzyskać podpowiedzi RStudio aby pokazać się podczas próby użycia metody klasy ... niestety nie myśl, że znajdziesz rozwiązanie, które nie wymaga kodowania twoich zajęć w sposób, który eliminuje wygodę i funkcjonalność klas R6.

@ f-privé dostarczył odpowiedź, która zrobi to, co chcesz - po prostu rozszerz ją na WSZYSTKIE metody. Na przykład, zamiast myclass$my_method jest dostępne przez

my_method = function(r6obj) { 
    r6obj$my_method() 
} 
obj$my_method() 
my_method(obj)  # equivalent 

Innymi słowy, trzeba by utworzyć otoki dla każdej metody. To oczywiście jest mniej wygodne w programowaniu niż po prostu używanie obj$my_method() i prawdopodobnie zabija to przede wszystkim przydatność używania klasy R6.

Kwestia tutaj jest naprawdę RStudio. IDE nie ma dobrego sposobu identyfikowania klas R6 poprzez analizę kodu i nie może rozróżniać metod zdefiniowanych klas od elementów listy lub środowiska. Ponadto RStudio nie może zapewnić pomoc w dowolnej funkcji, takich jak:

na.omit()   # tooltip shows up when cursor is within the parentheses 
foo = na.omit 
foo()    # no tooltip 

co jest dość analogicznie do metody wywołania konkretnego obiektu R6.

+0

Dzięki temu mam już miłą dokumentację w ramach pomocy! Nadal szukam pomocy w rStudio. To, co chciałbym mieć to autouzupełnianie i małe żółte okno pokazujące wywołanie funkcji z jej argumentami. W tej chwili otrzymuję nazwę funkcji zakończoną, ale bez podpowiedzi na temat argumentów. Muszę przeszukać za pomocą '? MQParameters', aby uzyskać pomoc i przeczytać sekcję metod. – drmariod

+0

@drmariod Edytowałem swoją odpowiedź, aby omówić problem z podpowiedziami, ale niestety nie sądzę, aby znaleźć satysfakcjonujące rozwiązanie w aktualnej wersji RStudio. – mikeck

+0

@mikeck Nie pamiętam, jak to się stało, ale możesz sprawdzić przykłady w text2vec - https://github.com/dselivanov/text2vec/blob/master/R/model_LSA.R. Po prostu pamiętam, że miałem również problemy ze znalezieniem najlepszego sposobu na udokumentowanie R6. –

2

Myślę, że ludzie R nie chcą używać numeru $new(...), aby uzyskać instancję nowej klasy. Wolą mieć funkcję o tej samej nazwie klasy, aby zbudować jej instancję.

Więc, co można zrobić, to zmienić nazwę R6ClassGenerator MQParameters_R6Class i utworzyć inną funkcję

MQParameters <- function(file_path = NA) { 
    MQParameters_R6Class$new(file_path) 
} 

Następnie dokument tę funkcję jak każdej innej funkcji, a dostaniesz „mały żółty okno pokazujące wywołanie funkcji z jego argumenty "z RStudio. I szczęśliwi użytkownicy R.

+0

Podoba mi się ten pomysł, ale nadal nie jestem z niego zadowolony! Myślę, że to lepszy sposób na programowanie! :-) Zobaczmy, czy są lepsze sugestie, ale dzięki, że mogę to rozważyć. – drmariod

Powiązane problemy