Arguments and classes for writing (common) functions in R

I want to make a small R package from a few very simple functions. In the literature, I use “Creating R-Packages: A Tutorial” and “Writing R-Extensions”. Although I tried, but I do not understand the concept of common functions and methods and how to process arguments in different functions.

Here is a small example of what my code looks like:

#Make generic function
f <- function(x,...) UseMethod("newmethod")

#Default method
f.default <- function(a,b=5,c=3,...){
    out <- a+b+c
    class(out) <- "fclass"
}

# Print method
print.f <- function(x,...){
    cat("Result:")
    print(x)
}

# Summary method
summary.f <- function(object,...){
    res <- object
    class(res) <- "fsummary"
    print(res)
}

# Plot method
plot.f <-function(x,p=0.3,...){}

f f.default. ( x), ? f.default( , ). plot.f f.default (). ? "" ""... , , ... ... , - .

-, , "" R- ( ).

+5
2

...

-, -, , /. - :

makefclass = function(a,b,c){
        l = list(a=a,b=b,c=c)
        class(l)="fclass"
        return(l)
      }

print.fclass:

print.fclass=function(x,...){
     cat("I'm an fclass!")
     cat("my abc is ",x$a,x$b,x$c,"\n")
}

:

> f=makefclass(1,2,3)
> f
I'm an fclass!my abc is  1 2 2 

, ...

+5

, ...

@Spacedman, "", , . , , .

#Make generic function
# This is the "constructor" function...
# ... UseMethod should have the name of the function!
f <- function(x,...) UseMethod("f")

#Default method
# ... The class name should be the same as the constructor
f.default <- function(a,b=5,c=3,...){
    out <- a+b+c
    class(out) <- "f"
    out # must return the object out, not the class name!
}

# Print method
# The "f" part of "print.f" must be the same as the class!
print.f <- function(x,...){
    cat("Result for f: ")
    print(unclass(x)) # Must unclass to avoid infinite recursion
    # NextMethod(x) # Alternative, but prints the class attribute...
}

# Summary method
# Should return a summary object (and not print it!)
# Need a unique class for it ("fsummary")
summary.f <- function(object,...){
    res <- object
    class(res) <- "fsummary"
    res
}

# Now need to print the summary too:
print.fsummary <- function(x, ...) {
    cat("f summary!\n")
    # Nice summary print goes here...
}

# Plot method
plot.f <-function(x,p=0.3,...){ cat("PLOTTING!\n") }

# Try it out:

x <- f(3)
x # print x

y <- summary(x) # 
y # print summary

plot(x)
+3

All Articles