I'm basically looking for the opposite of methods(some_function) , which returns all class-methods that exist for that function. Is there some easy way to search for all functions which have an explicit method for a given object class?
For example, methods(my_func) returns a pile of myfunc.classname values. Is there a functions(my_class) which would return all functions with a func.my_class method?
I think you want to supply an argument to class and nothing to generic.function in methods. Compare
methods(as.matrix)
[1] as.matrix.data.frame as.matrix.data.table* as.matrix.default
[4] as.matrix.dist* as.matrix.noquote as.matrix.POSIXlt
[7] as.matrix.raster* as.matrix.SpatialGridDataFrame* as.matrix.SpatialPixelsDataFrame*
With this, which returns methods for the generic class
methods(class="matrix")
[1] anyDuplicated.matrix as.data.frame.matrix as.data.table.matrix* as.raster.matrix* boxplot.matrix corresp.matrix*
[7] determinant.matrix duplicated.matrix edit.matrix* head.matrix isSymmetric.matrix lda.matrix*
[13] qda.matrix* relist.matrix* subset.matrix summary.matrix tail.matrix unique.matrix
Non-visible functions are asterisked
And this also seems to work for S4 classes as well, e.g.
methods(class="data.table")
[1] $<-.data.table* [.data.table* [<-.data.table* all.equal.data.table* as.data.frame.data.table*
[6] as.data.table.data.table* as.list.data.table* as.matrix.data.table* dim.data.table* dimnames.data.table*
[11] dimnames<-.data.table* duplicated.data.table* format.data.table* head.data.table* is.na.data.table*
[16] merge.data.table* na.omit.data.table* names<-.data.table* Ops.data.table* print.data.table*
[21] subset.data.table* tail.data.table* transform.data.table* unique.data.table* within.data.table*
I think you are describing the concept of introspection and reflection (well-known in Java).
A post about introspection and reflection in Java with links here : Java introspection and reflection
I don't know which technology or language you are using but maybe you will find the equivalent.
Hope this helps ! Bye !
Related
Just starting to use Julia, but I can't figure out how do you actually find the function signature in any of the docs...
For example, let's say I want to see what parameters the gradient function of the Flux package takes.
How can I find that? If I go to flux docs it's mostly english docs and not function signatures. Similar for julia docs.
Any tips appreciated.
Use the methods function to get a list of signatures of all methods of a given function. For example:
julia> methods(sin)
# 13 methods for generic function "sin":
[1] sin(x::BigFloat) in Base.MPFR at mpfr.jl:727
[2] sin(::Missing) in Base.Math at math.jl:1197
[3] sin(a::Complex{Float16}) in Base.Math at math.jl:1145
[4] sin(a::Float16) in Base.Math at math.jl:1144
[5] sin(z::Complex{T}) where T in Base at complex.jl:804
[6] sin(x::T) where T<:Union{Float32, Float64} in Base.Math at special/trig.jl:29
[7] sin(x::Real) in Base.Math at special/trig.jl:53
[8] sin(A::LinearAlgebra.Hermitian{var"#s827",S} where S<:(AbstractArray{var"#s828",2} where var"#s828"<:var"#s827") where var"#s827"<:Complex) in LinearAlgebra at /home/bkamins/julia/share/julia/stdlib/v1.5/LinearAlgebra/src/symmetric.jl:922
[9] sin(A::Union{LinearAlgebra.Hermitian{var"#s828",S}, LinearAlgebra.Symmetric{var"#s828",S}} where S where var"#s828"<:Real) in LinearAlgebra at /home/bkamins/julia/share/julia/stdlib/v1.5/LinearAlgebra/src/symmetric.jl:918
[10] sin(D::LinearAlgebra.Diagonal) in LinearAlgebra at /home/bkamins/julia/share/julia/stdlib/v1.5/LinearAlgebra/src/diagonal.jl:576
[11] sin(A::AbstractArray{var"#s828",2} where var"#s828"<:Real) in LinearAlgebra at /home/bkamins/julia/share/julia/stdlib/v1.5/LinearAlgebra/src/dense.jl:836
[12] sin(A::AbstractArray{var"#s828",2} where var"#s828"<:Complex) in LinearAlgebra at /home/bkamins/julia/share/julia/stdlib/v1.5/LinearAlgebra/src/dense.jl:843
[13] sin(J::LinearAlgebra.UniformScaling) in LinearAlgebra at /home/bkamins/julia/share/julia/stdlib/v1.5/LinearAlgebra/src/uniformscaling.jl:139
It seems that this function is lacking proper documentation and the standard approaches described in other answers (? for the help REPL or methods) will not be very useful.
What I normally do in such cases is to type something line:
#edit gradient(1,2)
This brings me to function definition (actually I can suspect the first parameter is a function but running methods did not indicate anything.
This will open the editor and you will see something like this:
function gradient(f, args...)
y, back = pullback(f, args...)
return back(sensitivity(y))
end
So at this stage you know what your function is doing. If not perhaps you can search for pullback typing ?pullback. When you do that you discover that there is no documentation for this neither but it is a part of Zygote.
However, typing into Google Zygote.pullback will forward you to the documentation you need: https://fluxml.ai/Zygote.jl/latest/adjoints/
So this is kind of hackish. Most of Julia libraries are nicely documented but if not I always start the job with #edit macro.
I am looking for the real object type of some functions in R, for example, I can not find out the object type of mean function.
> library(pryr)
> otype(mean)
[1] "base"
> ftype(mean)
[1] "s3" "generic"
Sometimes the mean function is S3 and sometimes it is base!
What does ftype tell us?
This function figures out whether the input function is a regular/primitive/internal function, a internal/S3/S4 generic, or a S3/S4/RC method. This is function is slightly simplified as it’s possible for a method from one class to be a generic for another class, but that seems like such a bad idea that hopefully no one has done it.
What does otype give us?
Figure out which object system an object belongs to:
• base: no class attribute
• S3: class attribute, but not S4
• S4: isS4, but not RC
• RC: inherits from "refClass"
For reference:
pryr package documentation
R language objects
I have used the setClass function to define several new classes. But these classes don't appear in my Rstudio environment. How do I see all the classes that exist?
Here is an example:
setClass("geckoNss", representation(absolute = "character", item = "list"))
The class now exists somewhere, as we can do
> getClass("geckoNss")
Class "geckoNss" [in ".GlobalEnv"]
Slots:
Name: absolute item
Class: character list
and make objects of that class:
> new("geckoNss")
An object of class "geckoNss"
Slot "absolute":
character(0)
Slot "item":
list()
Yet, I still do not see the class anywhere. BondedDust's answer suggests that you can only see these classes if you assign them to an object.
So is there no way to even see the default classes R comes with?
http://stat.ethz.ch/R-manual/R-devel/library/methods/html/Classes.html
"When a class is defined, an object is stored that contains the information about that class. The object, known as the metadata defining the class, is not stored under the name of the class (to allow programmers to write generating functions of that name), but under a specially constructed name. To examine the class definition, call getClass. The information in the metadata object includes: "
From the setClass help page, it's stored in the environment where it is created (by default) or in the specified with the "where" argument:
"Create a class definition, specifying the representation (the slots) and/or the classes contained in this one (the superclasses), plus other optional details. As a side effect, the class definition is stored in the specified environment. A generator function is returned as the value of setClass(), suitable for creating objects from the class if the class is not virtual."
After running a setClass call at the console you get an object in the global environment by that name:
> track <- setClass("track",
+ slots = c(x="numeric", y="numeric"))
> ls()
[1] "A" "AE_by_factors" "B"
[4] "dat" "dd" "df"
[7] "final" "hl" "len"
[10] "lm0" "ml" "ml0"
[13] "peas2" "realdata" "temp"
[16] "tolerance" "track" "TravelMode"
[19] "vbin" "vint" "vnum"
> track
class generator function for class “track” from package ‘.GlobalEnv’
function (...)
new("track", ...)
> class(track)
#----------
[1] "classGeneratorFunction"
attr(,"package")
[1] "methods"
Your question originally asked about S4 classes, i.e. the ones created with setClass.. It wasn't at all clear that you wanted to find S3 and what might be called default or implicit classes. They are managed in a different manner. If you want to see all the classes that exist for the print function, just type:
methods(print) # I get 397 different methods at the moment. Each one implies an S3 class.
# a variable number of values will appear depending on which packages ar loaded
Also read the help page for ?methods. Those are each dispatched on the basis of the class attribute. For classes, such as 'numeric', integer, character or 'list' that are implicit but not stored in object class-attributes youyou simply need to know that they were built into the original S language. The S3 dispatch mechanism was actually bolted on to that core S mechanism back in the dawn of time. S3 was part of the language when it was described by "New S Language". I currently see that you can still get used copies at Amazon:
New S Language Paperback – June 30, 1988
by R. A. Becker (Author), J. M. Chambers (Author), Allan R Wilks (Author)
There are other functions that allow you to look at the functions accessible along the search path:
> ?objects
> length(objects())
[1] 85
> length(apropos(what="", mode="function"))
[1] 3431
So on my machine a bit more than 10% of the available functions are print methods.
I don't know , if this is the correct place to ask subjective questions and I am fairly new to R, but i am really confused at this time.I was going through R-Language reference and found two objects by running typeof(is.na) and typeof(mean) which returned "builtin" and "closure" respectively on R prompt. I don't know what does it mean, I went to this site after searching, http://www.r-bloggers.com/closures-in-r-a-useful-abstraction/ , but unable to understand , Can anyone help me in understanding "closure" and "builtin" in some layman terms?
From help("closure"):
This type of function is not the only type in R: they are called
closures (a name with origins in LISP) to distinguish them from
primitive functions.
From help(".Primitive"):
a ‘primitive’ (internally implemented) function.
"internally implemented" is just a different term for "builtin".
Both (closures and primitives) are functions in R. A primitive function is implemented exclusively in C (with a special calling mechanism), a closure (mostly) in R.
Another distinction between them is, that a closure always has an environment associated with it (see the language definition). That's actually pretty much the definition of "closure".
function clousures, or simply functions, are made of three basic components: formals, body and environment.
The environment, or better the enclosing environment, of a function is the environment where the function is created and functions do remember it ...
> typeof(mean)
[1] "closure"
> environment(mean)
<environment: namespace:base>
> environment(function(x){x+1})
<environment: R_GlobalEnv>
Primitives, as opposite to closures, do not have an environment:
> typeof(sum)
[1] "builtin"
> environment(sum)
NULL
In practice, closures and Primitives, differ in the way arguments are passed to the internal function.
If we want to check if a function is a closure or primitive, we may use:
> is.primitive(sum)
[1] TRUE
> is.primitive(mean)
[1] FALSE
methods(print)
omitted many outputs
[175] print.vignette* print.warnings print.xgettext*
[178] print.xngettext* print.xtabs*
Non-visible functions are asterisked
how can i get the function on print which has no asteriske at the end ?
print.warnings should be displayed ,print.xtabs* should not be displayed.
methods(print)->x
x[grep("^//*",x)]
x[grep("^*",x)]
it is failure.
The asterisks aren't really part of the string (so they won't be detected by applying grep to the strings, even if you get the regular expression incantation right), they're appended by the print.MethodsFunction method. Maybe this will do what you want:
methods(print)->x
vis <- attr(x,"info")[,"visible"]
x[!vis]
x[vis]
(I figured this out by looking at the output of str(x))