Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking at internal Methods

Tags:

r

I'd like to be able to see the function that's used when I use str(), as I'd like to modify it a bit for my own purposes as another function.

When I type str(), I get the following:

function (object, ...) 
UseMethod("str")
<environment: namespace:utils>

So I tried, getAnywhere(str):

2 differing objects matching ‘str’ were found
in the following places
  .GlobalEnv
  package:utils
  namespace:utils
Use [] to view one of them

But there's nothing in the documentation about what the syntax should be for using []

So I tried, getAnywhere(str)[1]:

function (object, ...) 
UseMethod("str")
<environment: namespace:utils>

Sigh. Allright, what about showMethods(str):

Function "str":
 <not a generic function>

So, how do I see the construction of the output for str()? Or can I?

like image 676
Brandon Bertelsen Avatar asked Apr 29 '11 17:04

Brandon Bertelsen


2 Answers

You want methods() for an S3 generic such as str():

> methods(str)
[1] str.data.frame* str.Date*       str.default*   
[4] str.dendrogram* str.logLik*     str.POSIXt*    

   Non-visible functions are asterisked

Using getAnywhere(str) is not really helpful because str() is visible so you get the same result if you just run str at the prompt. You need getAnywhere() to look at the hidden methods listed above:

getAnywhere(str.default)

for example.

Shame you need to know what kind of generic a function is to list the methods; seems user-friendliness would be improved if R didn't care what kind of method type was supplied to one or other of these functions.

like image 115
Gavin Simpson Avatar answered Nov 15 '22 21:11

Gavin Simpson


You could also do it like this:

> methods(by)
[1] by.data.frame by.default
> getS3method("by", "data.frame")
function (data, INDICES, FUN, ..., simplify = TRUE) 
{
   ...
}
<environment: namespace:base>
like image 44
Roman Luštrik Avatar answered Nov 15 '22 23:11

Roman Luštrik