Jan Kislinger
Jan Kislinger

Reputation: 1563

Change an element of global vector in a function

I have a vector in global environment and I want to create a function that modifies only one element of that vector. The problem is that the vector is too large and standard methods take too long to compute. See functions I already have, both of them are too slow.

x <- rep(0, 1e8)
f1 <- function(n,a) {
  x <- x      # loads the vector to current environment
  x[n] <- a   # changes the position in current environment
  x <<- x     # saves the vector to global environment
}
f2 <- function(n,a) {
  x[n] <<- a  # changes the vector element in global environment
}

system.time(f1(1,1))   # 0.34
system.time(f2(2,1))   # 0.30
system.time(x[3] <- 1) # 0.00

I am looking for something like this:

assign('x[4]', 1, .GlobalEnv)

Upvotes: 2

Views: 1258

Answers (1)

Eric Lecoutre
Eric Lecoutre

Reputation: 1481

For me, you can address this with data.table package as it manipulates object by reference.

For instance:

library(data.table)
data <- data.table(x=rep(0, 1e8))

f3 <- function(n,a){ 
  data[n,x:=a]
  return(TRUE)  
}

system.time(f3(2,1))   # 0
print(data)
x
1: 0
2: 1
3: 0
4: 0
...

You can retrieve x as vector at any time with data[["x"]]

Upvotes: 1

Related Questions