2015-12-27 45 views
-1

我在R中創建了函數矩陣,但是當我將它們稱爲x「row1」,「column1」時,出現錯誤「嘗試應用於非功能」。只看輸出與(),我看到在R中創建函數矩陣 - 但調用時試圖應用非函數

function() 
{ 
    mycodehere 
} 

<environment: 0x00000000159a0790> 

這將看起來是一個鑄造問題。我是否需要將其轉換爲函數或其他?

我試過查找別人如何定義函數矩陣,我沒有看到任何類似於我正在做的事情。這甚至有可能嗎?

+0

看看這個解決您的問題:http://stackoverflow.com/questions/12481404/how-to-create-a-vector-of-functions –

回答

0

矩陣是一個簡單的維度原子向量或列表。你不能建立一個函數向量,但你可以建立一個函數列表。 (注意:嘗試構建函數向量會自動返回函數列表。)

當您有「列表矩陣」時,必須使用雙括號索引來訪問單元格的內容;單括號索引只是返回另一個列表,索引組件作爲唯一組件。

for (i in 1:6) assign(paste0('f',i),{ f <- function() x; body(f) <- i; f; },globalenv()); 
f1; f2; f3; f4; f5; f6; ## 6 simple functions 
## function() 
## 1L 
## function() 
## 2L 
## function() 
## 3L 
## function() 
## 4L 
## function() 
## 5L 
## function() 
## 6L 
f1(); f2(); f3(); f4(); f5(); f6(); ## each returns an integer 
## [1] 1 
## [1] 2 
## [1] 3 
## [1] 4 
## [1] 5 
## [1] 6 
m <- matrix(list(f1,f2,f3,f4,f5,f6),3L,2L); ## build a dimensioned list of functions 
m; 
##  [,1] [,2] 
## [1,] ? ? 
## [2,] ? ? 
## [3,] ? ? 
m[3L,2L]; ## single-bracket indexing returns the list component 
## [[1]] 
## function() 
## 6L 
## 
m[3L,2L](); ## you can't "run" a list 
## Error: attempt to apply non-function 
m[[3L,2L]]; ## double-bracket indexing returns the list component value: the function 
## function() 
## 6L 
m[[3L,2L]](); ## run the function 
## [1] 6 
m[3L,2L][[1L]](); ## alternative 
## [1] 6 
+0

明白了,我需要的雙支架返回實際功能而不是列表。謝謝你對這個明顯的新手問題非常有幫助和道歉。 –