methods: Formal Methods and Classes

> library(methods)

バージョン: 3.2.3


関数名 概略
.BasicFunsList List of Builtin and Special Functions
Classes Class Definitions
Documentation Using and Creating On-line Documentation for Classes and Methods
GenericFunctions Tools for Managing Generic Functions
LinearMethodsList-class Class "LinearMethodsList"
LocalReferenceClasses Localized Objects based on Reference Classes
MethodDefinition-class Classes to Represent Method Definitions
MethodWithNext-class Class MethodWithNext
Methods General Information on Methods
MethodsList-class Class MethodsList, Defunct Representation of Methods
ObjectsWithPackage-class A Vector of Object Names, with associated Package Names
ReferenceClasses Objects With Fields Treated by Reference (OOP-style)
S3Part S3-style Objects and S4-class Objects
S4groupGeneric S4 Group Generic Functions
SClassExtension-class Class to Represent Inheritance (Extension) Relations
as Force an Object to Belong to a Class
callGeneric Call the Current Generic Function from a Method
callNextMethod Call an Inherited Method
canCoerce Can an Object be Coerced to a Certain S4 Class?
cbind2 Combine two Objects by Columns or Rows
character-class Classes Corresponding to Basic Data Types
className Class names including the corresponding package
classRepresentation-class Class Objects
classesToAM Compute an Adjacency Matrix for Superclasses of Class Definitions
dotsMethods The Use of '...' in Method Signatures
envRefClass-class Class '"envRefClass"'
environment-class Class '"environment"'
evalSource Use Function Definitions from a Source File without Reinstalling a Package
findClass Computations with Classes
findMethods Description of the Methods Defined for a Generic Function
fixPre1.8 Fix Objects Saved from R Versions Previous to 1.8
genericFunction-class Generic Function Objects
getClass Get Class Definition
getMethod Get or Test for the Definition of a Method
getPackageName The Name associated with a Given Package
hasArg Look for an Argument in the Call
implicitGeneric Manage Implicit Versions of Generic Functions
inheritedSlotNames Names of Slots Inherited From a Super Class
initialize-methods Methods to Initialize New Objects from a Class
is Is an Object from a Class?
isSealedMethod Check for a Sealed Method or Class
language-class Classes to Represent Unevaluated Language Objects
makeClassRepresentation Create a Class Definition
method.skeleton Create a Skeleton File for a New Method
methods-package Formal Methods and Classes
new Generate an Object from a Class
nonStructure-class A non-structure S4 Class for basic types
promptClass Generate a Shell for Documentation of a Formal Class
promptMethods Generate a Shell for Documentation of Formal Methods
representation Construct a Representation or a Prototype for a Class Definition
selectSuperClasses Super Classes (of Specific Kinds) of a Class
setClass Create a Class Definition
setClassUnion Classes Defined as the Union of Other Classes
setGeneric Define a New Generic Function
setLoadActions Set Actions For Package Loading
setMethod Create and Save a Method
setOldClass Register Old-Style (S3) Classes and Inheritance
show Show an Object
showMethods Show all the methods for the specified function(s) or class
signature-class Class '"signature"' For Method Definitions
slot The Slots in an Object from a Formal Class
structure-class Classes Corresponding to Basic Structures
testInheritedMethods Test for and Report about Selection of Inherited Methods
traceable-class Classes Used Internally to Control Tracing
validObject Test the Validity of an Object

as

オブジェクトクラスの強制変換

> data.frame(a = c(1, 2, 3),
+            b = c("a", "b", "c")) %>% {
+              print(class(.))
+              as(., "list") %>% class()
+            }
[1] "data.frame"
[1] "list"

is / extends / setIs

オブジェクトクラスの確認

methods / .S3methods

S3,S4クラスの総称関数やクラスのメソッド一覧を取得

Arguments

  • generic.function... 総称関数を関数名か文字列で渡す
  • class
  • envir
> methods(generic.function = "summary")
 [1] summary,ANY-method             summary,DBIObject-method      
 [3] summary,mle-method             summary,stanfit-method        
 [5] summary.aov                    summary.aovlist*              
 [7] summary.aspell*                summary.check_packages_in_dir*
 [9] summary.connection             summary.data.frame            
[11] summary.Date                   summary.default               
[13] summary.Duration*              summary.ecdf*                 
[15] summary.factor                 summary.ggplot*               
[17] summary.glm                    summary.infl*                 
[19] summary.Interval*              summary.lm                    
[21] summary.loess*                 summary.manova                
[23] summary.matrix                 summary.mlm*                  
[25] summary.nls*                   summary.packageStatus*        
[27] summary.PDF_Dictionary*        summary.PDF_Stream*           
[29] summary.Period*                summary.POSIXct               
[31] summary.POSIXlt                summary.ppr*                  
[33] summary.prcomp*                summary.princomp*             
[35] summary.proc_time              summary.shingle*              
[37] summary.srcfile                summary.srcref                
[39] summary.stepfun                summary.stl*                  
[41] summary.table                  summary.trellis*              
[43] summary.tukeysmooth*           summary.XMLInternalDocument*  
[45] summary.yearmon*               summary.yearqtr*              
[47] summary.zoo*                  
see '?methods' for accessing help and source code
> methods(class = "glm")
 [1] add1           anova          coerce         confint       
 [5] cooks.distance deviance       drop1          effects       
 [9] extractAIC     family         formula        influence     
[13] initialize     logLik         model.frame    nobs          
[17] predict        print          residuals      rstandard     
[21] rstudent       show           slotsFromS3    summary       
[25] vcov           weights       
see '?methods' for accessing help and source code
> methods("dim") %>% attr("info")
               visible                        from generic  isS4
dim.data.frame    TRUE                        base     dim FALSE
dim.gtable       FALSE registered S3method for dim     dim FALSE
dim.idf          FALSE registered S3method for dim     dim FALSE
dim.layout       FALSE registered S3method for dim     dim FALSE
dim.stanfit      FALSE registered S3method for dim     dim FALSE
dim.tbl_cube     FALSE registered S3method for dim     dim FALSE
dim.tbl_sql      FALSE registered S3method for dim     dim FALSE
dim.trellis      FALSE registered S3method for dim     dim FALSE

new

クラスからオブジェクトを生成する

> new(Class = "track", 
+     x = -4:4, 
+     y = exp(-4:4)) %>% 
+   {
+     print(class(.))
+     .
+   }
Error in getClass(Class, where = topenv(parent.frame())): "track" is not a defined class

setClass

クラス定義を行う

Arguments

  • Class... クラスの名称(文字列)
  • slots
  • contains
  • prototype
  • where
  • validity
  • S3methods, representation, access, version... R 3.0.0 から無効。
  • sealed
  • package
> setClass(Class     = "track",
+          slots     = c(x = "numeric", y = "numeric"),
+          prototype = list(x = numeric(), y = numeric()))

slot

スロットへのアクセス

> setClass(Class     = "track",
+          slots     = c(x = "numeric", y = "numeric"),
+          prototype = list(x = numeric(), y = numeric()))
Error in assign(mname, def, where): cannot add bindings to a locked environment
> myTrack <- new("track", x = -4:4, y = exp(-4:4))
Error in getClass(Class, where = topenv(parent.frame())): "track" is not a defined class
> slot(object = myTrack, name = "x")
Error in slot(object = myTrack, name = "x"): object 'myTrack' not found
> myTrack@y
Error in eval(expr, envir, enclos): object 'myTrack' not found