1

Probably this question is already answered but I'm not sure if it was exactly the same kind of answer I want. I search here and in other sites but neither as useful to me.

I'd like to understand how to create a variable with a reference to another in R.

Like:

Imagine I have this:

a <- c(1,2,3,4,5)
b <- c("a","b","c","d")

Now, I know I may do this:

c <- list(
    var.a = list( 
        description = "this is var.a",
        data = a ),
    var.b = list( 
        description = "this is var.b",
        data = b ) )

The code above didn't create a reference. Because If I do:

c$data$a[2] <- 99

See what I got:

c$data$a
# 1 99 3 4 5
a
# 1 2 3 4 5

So, what I'd like to have is somehow got this behavior below:

c$data$a[2] <- 99
c$data$a
# 1 99 3 4 5
a
# 1 99 3 4 5

Maybe this is a very silly simple question but any help is appreciable.

Thanks in advance

Aureliano Guedes
  • 767
  • 6
  • 22
  • I don't think this is possible in `R`. Now I am curious to know too – Telepresence Aug 31 '19 at 22:48
  • 1
    Related and relevant: [Can you pass-by-reference in R?](https://stackoverflow.com/questions/2603184/can-you-pass-by-reference-in-r); from the first answer to that post: "*Objects in assignment statements are immutable. R will copy the object not just the reference.*" – Maurits Evers Aug 31 '19 at 22:52
  • 1
    But also check reference classes, as mentioned in one of the answers from the question linked by Maurits. – Alexis Aug 31 '19 at 22:55
  • I saw this question @MauritsEvers mentioned as I saw others sites too. Reference classes seems quiet noise, if I would like to modify constantily, but S4 (which I need to study a little more) seems solve part of the problem. I don't understand why R choose this behavior. – Aureliano Guedes Aug 31 '19 at 23:03
  • 1
    The use of `environment`s allow pass-by-reference without ref-classes or other complexities. (If I remember correctly, ref-classes use environments for this purpose and others.) – r2evans Sep 01 '19 at 06:05
  • 1
    if you're working with `data.frame`, say, you could switch to `data.table` and when you set `dt <- df`, then `dt` 'refers' to df and is not a copy. Not sure if that exists for other R data types – Gautam Sep 02 '19 at 00:48

0 Answers0