R equivalent to the Python function "dir"? - r

Is there a function in R that can tell me the attributes of a given object (or class)?
Consider the "dir" function in python when passed the file class:
>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__',
'__format__', '__getattribute__', '__hash__', '__init__', '__iter__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'close', 'closed',
'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name',
'newlines', 'next', 'read', 'readinto', 'readline', 'readlines',
'seek', 'soft space', 'tell', 'truncate', 'write', 'writelines',
'xreadlines']
Maybe there is an equivalent of type as well(?)
>>> type(1)
<type 'int'>

R makes several different object oriented systems available to you, so if you don't know what species of object you're dealing with, you'll first need to determine whether it is one of S3, S4, or RC. Use isS4(x) and is(x, 'refClass') for this. If it's not S4 and not RC, it's S3. See Hadley's Advanced R chapter on object oriented programming for more information.
For S3 and S4 objects there are several functions you need to call to get information equivalent to Python's dir. All of these methods will require you to supply the name of the class of the object as an argument, which you can determine with the class function.
For methods, use methods(class=class(x)) for S3 objects and showMethods(class=class(x)) for S4 objects. To reveal "attribute" names/values, use attributes(x) for S3 objects and getSlots(class(x)) for S4 objects. Note, getSlots will only show the slot names and types, not their values. To access the values, you'll have to use slot, but these values should also print when you simply print the object to the console.

Related

what is the object type of mean in R?

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

Determine class type in R (S3 vs S4)

Is there any way to determine if an R object is S3 or S4 class?
For example class(x) just returns the object name but not its type.
You can use isS4(my_object) to determine whether it is an S4 object. Additionally, str should also tell you (look at the top, starts with "Formal Class ...").

How do I see existing classes

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.

Function signature not found despite showing with methods(...)

I am new to Julia, so this might be trivial.
I have a function definition within a module that looks like (using URIParser):
function add!(graph::Graph,
subject::URI,
predicate::URI,
object::URI)
...
end
Outside of the module, I call:
add!(g, URIParser.URI("http://test.org/1"), URIParser.URI("http://test.org/2"), URIParser.URI("http://test.org/1"))
Which gives me this error:
ERROR: no method add!(Graph,URI,URI,URI)
in include at boot.jl:238
in include_from_node1 at loading.jl:114
at /Users/jbaran/src/RDF/src/RDF.jl:79
Weird. Because when I can see a matching signature:
julia> methods(RDF.add!)
# 4 methods for generic function "add!":
add!(graph::Graph,subject::URI,predicate::URI,object::Number) at /Users/jbaran/src/RDF/src/RDF.jl:29
add!(graph::Graph,subject::URI,predicate::URI,object::String) at /Users/jbaran/src/RDF/src/RDF.jl:36
add!(graph::Graph,subject::URI,predicate::URI,object::URI) at /Users/jbaran/src/RDF/src/RDF.jl:43
add!(graph::Graph,statement::Statement) at /Users/jbaran/src/RDF/src/RDF.jl:68
At first I thought it was my use of object::Union(...), but even when I define three functions with Number, String, and URI, I get this error.
Is there something obvious that I am missing? I am using Julia 0.2.1 x86_64-apple-darwin12.5.0, by the way.
Thanks,
Kim
This looks like you may be getting bit by the very slight difference between method extension and function shadowing.
Here's the short of it. When you write function add!(::Graph, ...); …; end;, Julia looks at just your local scope and sees if add! is defined. If it is, then it will extend that function with this new method signature. But if it's not already defined locally, then Julia creates a new local variable add! for that function.
As JMW's comment suggests, I bet that you have two independent add! functions. Base.add! and RDF.add!. In your RDF module, you're shadowing the definition of Base.add!. This is similar to how you can name a local variable pi = 3 without affecting the real Base.pi in other scopes. But in this case, you want to merge your methods with the Base.add! function and let multiple dispatch take care of the resolution.
There are two ways to get the method extension behavior:
Within your module RDF scope, say import Base: add!. This explicitly brings Base.add! into your local scope as add!, allowing method extension.
Explicitly define your methods as function Base.add!(graph::Graph, …). I like this form as it more explicitly documents your intentions to extend the Base function at the definition site.
This could definitely be better documented. There's a short reference to this in the Modules section, and there's currently a pull request that should be merged soon that will help.

Adding character values to a generic type

What generic type should i use, if I have to assign a Character value to it?
For now I'm using type Char is(<>); at the generic declaration,
and assign the character value like this:
XY:GenericChar;
CharacterVariable: Character:='A';
XY:=GenericChar'Value(Character'Image(CharacterVariable));
It works, but i think there should be a better way.
You could use 'Pos and 'Val.
Converting between non-related enumeration types is non-trivial. Best would be to use a conversion function like:
generic
type Generic_Char is (<>);
with function To_Generic_Char (Source : Character) return Generic_Char is <>;
package Foo is
...
That way your generic package wouldn't have to care about converting.
For instantiating the package you would have to create the function.
That generic formal parameter you are using can be supplied with any "discrete type". That means that the client can use any kind of integer-related type, or an enumeration, to instantiate your generic. It also means that only operations available to both integers and enumerations are available inside the routine.
For the most part that means you can assign Chars, you can compare them, and you have access to any attribute available to "discretes". Checking our handy-dandy online LRM page for language-defined attributes (keep this bookmarked while working with generics), looking for ones that work with "discrete" or "scalar" objects/types, we see that this includes:
'first
'image
'last
'max
'min
'pred
'range
'succ
'val
'value
(assorted wide_ variants of 'image and 'value)
The usual suspects available to all objects of any type (eg: 'size, 'input, etc.)

Resources