2011-11-25 43 views
13

關於R的一個關於kool的事情是,如果我輸入函數名稱來查看實現。但是這一個是困惑我,遞歸:useMethod是什麼意思?

> library(xts) 
> align.time 
function (x, ...) 
{ 
    UseMethod("align.time") 
} 
<environment: namespace:xts> 

x是XTS對象,所以並不意味着它會調用XTS align.time方法......但是這就是我在看! (打字xts::align.time給人如出一轍的迴應。)

+2

也見這個非常類似的問題:http://stackoverflow.com/q/5835312/602276 HTTP的 – Andrie

+1

圈7:// WWW。 burns-stat.com/pages/Tutor/R_inferno.pdf可能會幫助你獲得一種什麼樣的通用功能和方法的感覺。 –

+0

@PatrickBurns謝謝,這看起來像一個有用的閱讀。 –

回答

16

簡而言之,您正在尋找功能xts:::align.time.xts

較長的答案是,你可以找到哪些方法調用methodsalign.time存在:

> methods(align.time) 
[1] align.time.POSIXct* align.time.POSIXlt* align.time.xts*  

    Non-visible functions are asterisked 

這告訴你,有一個方法align.time.xts未從命名空間中導出。在這一點上,你可能已經猜到,它可以在包xts被發現,但可以確認與getAnywhere

> getAnywhere("align.time.xts") 
A single object matching 'align.time.xts' was found 
It was found in the following places 
    registered S3 method for align.time from namespace xts 
    namespace:xts 
with value 

function (x, n = 60, ...) 
{ 
    if (n <= 0) 
     stop("'n' must be positive") 
    .xts(x, .index(x) + (n - .index(x)%%n), tzone = indexTZ(x), 
     tclass = indexClass(x)) 
} 
<environment: namespace:xts> 

你可以,當然,直接讀取源,但由於功能沒有出口,則需要使用package:::function(即三個冒號):

> xts:::align.time.xts 
function (x, n = 60, ...) 
{ 
    if (n <= 0) 
     stop("'n' must be positive") 
    .xts(x, .index(x) + (n - .index(x)%%n), tzone = indexTZ(x), 
     tclass = indexClass(x)) 
} 
<environment: namespace:xts> 
7

align.time()XTS出口命名空間,因此xts::align.timealign.time是一樣的。你需要注意,在包中提供"xts"類對象的align.time()方法不是從命名空間出口(這是剛剛註冊爲S3的方法):

> xts:::align.time.xts 
function (x, n = 60, ...) 
{ 
    if (n <= 0) 
     stop("'n' must be positive") 
    .xts(x, .index(x) + (n - .index(x)%%n), tzone = indexTZ(x), 
     tclass = indexClass(x)) 
} 
<environment: namespace:xts> 

正是這種方法當您將"xts"對象傳遞給align.time()時會被調用。

當您致電align.time()UseMethod()設置搜索並調用適當的"align.time"方法(如果可用),作爲第一個參數提供的對象的類。 UseMethod正在做你認爲它正在做的事情,你只是通過兩種不同的方式來看待相同的功能(泛型)而使自己感到困惑。

+0

+1來彌補;-) – Andrie

+1

:-)馬上回到你身邊。 OP在決定授予接受時還應考慮我們各自代表概況的一階導數。你遲到了! ;-) –