Reputation: 196
I'm having a lot of trouble understanding the semantics and grammar of R. It appears to me that local variables aren't able to be modified inside of a function.
As an example, in this basic code, I would expect the heatmap.matrix
variable to get updated when I call the foo()
function.
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
This leads me to believe that the scope of variables isn't passed back after the function evaluates. Is that the case with R? Is something else going on? I feel like I really don't have a hang on what's going on. Any help/insight would really be appreciated!
To give a quick explanation, in my code, I have a frequency table with x
and y
columns, and I'm trying to convert that into a 2-D matrix with the value corresponding to entry in the frequency table, or zero if there is no corresponding entry. However, I'm unable to modify my matrix within an apply function.
Upvotes: 0
Views: 528
Reputation: 2832
It is possible to update a global variable, in a function using get
and assign
function. Below is the code, which does the same :
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
you should read up a bit on environments concept. The best place to start is http://adv-r.had.co.nz/Environments.html
Upvotes: 1