Bridgeburners
Bridgeburners

Reputation: 657

Reference object from environment without assignment

I have a function that looks like this:

sampleFcn <- function(c1, c2) {
  chars <- get('chars', envir=.GlobalEnv)
  if (c1 %in% chars) { 
    array[c1,1] <<- array[c1,1] + 1
    if (c2 %in% chars)  bigM[c1,c2] <<- bigM[c1,c2] + 1
  }
}

This will be applied across a large data set. As it is now, it works but it takes very long to apply, and I'm guessing that's mostly because of the second line, where I'm constantly assigning, to a new variable, a large vector (chars). My question is, how do I call the global variable 'chars' without having to constantly use new memory to assign it with the 'get' function?

Upvotes: 0

Views: 54

Answers (1)

joran
joran

Reputation: 173627

I would rethink your assumptions about where your code is inefficient:

library(pryr)
x <- matrix(1:1e6,10)
> object_size(x)
4 MB

track_x <- track_copy(x)

foo <- function(){
    r1 <- mem_change(s <- get("x",.GlobalEnv))
    r2 <- mem_change(2 %in% s)
    list(r1,r2)
}

> foo() #No noticeable memory use
[[1]]
14 kB

[[2]]
1.74 kB


> track_x()
# Nothing changed

> mem_changed(x[1,1] <- x[1,1]+1)
4MB #Increased by 4MB

> track_x()
x copied #Because it copied

Upvotes: 1

Related Questions