2016-02-16 74 views
0

我試圖更新一個全局變量(矩陣名: 「confusion.mat」):[R局部全局變量

confusion.mat <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(3L, 3L)) 
intersection.list <- c(1, 2) 

然而,全局變量混亂的功能

register.hit <-function(categ){ 
    confusion.mat[categ,categ] = confusion.mat[categ,categ] + 1 
    } 
sapply(intersection.list,register.hit) 

數據中.mat沒有更新(在調試模式下,我注意到函數register.hit中的局部變量confusion.mat已正確更新)。 任何幫助表示讚賞

+0

你能製作一個可重現的例子嗎?我似乎無法在'R'中重新創建問題。 – Ruben

+0

這是設計。 '功能'不應該有副作用。如果你的函數返回一些東西,可以使用'apply'函數。否則留一個'for'循環。當然,可能會有更好的向量化解決方案,但是你並沒有描述你實際想要達到的目標。 – Roland

+0

也許這是你的目標? 'diag(confusion.mat)< - seq_len(nrow(confusion.mat))' – Roland

回答

0

廣泛的谷歌搜索後,我發現,運營商< < - 被分配的功能範圍內的全局變量 所以我相應地改變我的代碼:

register.hit <-function(categ){ 
    confusion.mat[categ,categ] <<- confusion.mat[categ,categ] + 1 
    } 

和它的作品

+0

不要使用'<< - '。這是專家而不是新手,不知道這個運營商的危險。在你的網頁搜索過程中,你應該看到一些警告,反對使用'<< - '。 – Roland

+0

我不會對'<< - '這麼謹慎。 'sapply'不會使全局情感作爲基本的'for',因爲它被用作'res < - sapply(...'。它不是針對更新值而是計算並返回結果 – clemlaflemme

0

以下是實現相同結果的矢量化方法:

confusion.mat <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(3L, 3L)) 
confusion.mat[cbind(intersection.list, intersection.list)] <- 
    confusion.mat[cbind(intersection.list, intersection.list)] + 1 
#  [,1] [,2] [,3] 
#[1,] 1 0 0 
#[2,] 0 1 0 
#[3,] 0 0 0