2014-02-07 15 views
1

我有一個d維矢量參數的函數,我試圖在一個簡單的例子d=2在常規網格上計算它的值。這是很自然的嘗試outer這裏,它完美的作品,即,在簡單情況下調用外部產品沒有向量化的FUN參數

> outer(1:2, 3:4, function(x, y) x+y) 
    [,1] [,2] 
[1,] 4 5 
[2,] 5 6 

然而,我的功能並不支持自然矢量。爲了說明,認爲像

> outer(1:2, 3:4, function(x, y) length(c(x, y))) 

與期望的輸出(顯然,從上面的代碼的實際結果是錯誤的)

 [,1] [,2] 
[1,] 2 2 
[2,] 2 2 

我的當前的解決方法是沿apply(expand.grid(1:2, 3:4), 1, length)線的東西,但對我來說看起來有點笨拙。對於這種情況,有沒有像outer一樣簡單?

+0

一些[歷史在這裏(HTTP:// stackoverflow.com/questions/21445605/r-outer-matrices-and-vectorizing/21446738#21446738),它還將評論鏈接回早期的@agstudy帖子。 – BrodieG

+0

感謝您的鏈接。 – tonytonov

回答

5

要麼你 「向量化」 使用Vectorize你的函數:

outer(1:2, 3:4, Vectorize(function(x, y) length(c(x, y)))) 
    [,1] [,2] 
[1,] 2 2 
[2,] 2 2 

或者繼續使用expand.grid同樣的想法,但mapply

xx = expand.grid(1:2, 3:4) 
mapply(function(x, y) length(c(x, y)), xx$Var1, xx$Var2) 
[1] 2 2 2 2 
+0

+1顯示兩個答案。 – BrodieG

+0

感謝這兩個想法。我認爲不可能把我的電話打包成'Vectorize';事實證明,事實並非如此。 – tonytonov

+0

@BrodieG謝謝你是紳士。 – agstudy