2016-07-05 83 views
0

我在理解R的語義和語法方面遇到了很多麻煩。在我看來,局部變量不能在函數內部修改。R中的函數內部可以修改非全局變量嗎?

舉個例子,在這個基本的代碼,我希望當我打電話了foo()功能heatmap.matrix變量得到更新。

heatmap.matrix <- matrix(rep(0,40000), nrow=200, ncol=200) 

# foo function should just update a single cell of the declared matrix 
foo <- function() { heatmap.matrix[40,40] <- 100} 

heatmap.matrix[40,40] 
[1] 0 
foo() 
heatmap.matrix[40,40] 
[1] 0 
# there I expected it to return 100. Yet if I do it out of the function: 
heatmap.matrix[40,40] <- 100 
[1] 100 

這使我相信,變量的範圍不傳回的函數計算後。 這是R的情況嗎?還有其他事情嗎?我覺得我真的不知道發生了什麼。任何幫助/見解將真正被讚賞!

爲了快速說明,在我的代碼中,我有一個包含xy列的頻率表,我試圖將其轉換爲一個2-D矩陣,其值對應於頻率表中的條目,如果沒有相應的條目,則爲零。但是,我無法在應用函數中修改我的矩陣。

+2

雙賦值運算符'<< - '用於修改函數外部的變量。另外,請閱讀[函數](http://adv-r.had.co.nz/Functions.html)和詞彙範圍 – SymbolixAU

+3

'foo()'獲取'heatmap.matrix'的一個副本,並在裏面修改它功能。全局'heatmap.matrix'永遠不會被修改。通常,R需要一個對象的副本,進行修改,然後返回整個對象,如'foo < - function(){heatmap.matrix [40,40] < - 100; heatmap.matrix}' – thelatemail

+2

你可以使用'<< - '在本地環境之外進行分配,但它通常是不好的形式。最好是返回改變後的對象,所以從代碼中可以清楚地看到,你正在重新分配變量,並且沒有任何東西會被無形地改變。 '<< - '也是有點危險的,因爲根據你的結構和變量名稱(以及其他父級環境中的名稱),它可能不會指定你想要的位置,這可能會給你帶來bug,或者更糟糕的是,誰沒有源代碼。 – alistaire

回答

1

可以在使用getassign函數的函數中更新全局變量。下面是代碼,它是這樣做的:

heatmap.matrix <- matrix(rep(0,40000), nrow=200, ncol=200) 

# foo function should just update a single cell of the declared matrix 
varName <- "heatmap.matrix" 
foo <- function() { 
    heatmap.matrix.copy <- get(varName) 
    heatmap.matrix.copy[40,40] <- 100 
    assign(varName, heatmap.matrix.copy, pos=1) 
} 

heatmap.matrix[40,40] 
#[1] 0 
foo() 
heatmap.matrix[40,40] 
# [1] 100 

你應該閱讀一下環境概念。開始的最佳位置是http://adv-r.had.co.nz/Environments.html

+0

謝謝,我認爲這和上面的評論回答了我的問題。我猜R就像Lisp那樣會返回所有東西的新副本。 –