for to change a vector from a function

Say I have a function that runs an expensive for loop something like this. and A vector I want to change. How can I pass by reference in R.

f1 <- function(x){
  for(i in seq_along(x)){
    x[[i]] <- i
  }
}

x <- sample(x = 1:1e5,
            size = 1e5,
            replace = TRUE)

f1(x)

If you run the code below nothing in x would change everything will work on a copy of x. But in case X is huge and I don't want to copy it. How can I change it in place.

f2 <- function(x){
  for(i in seq_along(x)){
    x[[i]] <<- i
  }
}

This functions works but for weird reasons. I don't really want to use it. Do any of you have anything other than rcpp to solve such problem. I am just looking for suggestions.

I guess I would reconceptualize my vector as a column of a data.table and take advantage of data.tables ability to modify/ work by reference

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

Vectors are faster and save a lot of memory too... Hence I wanted it to be on vectors not on data.table which is a mutable object